const API_BASE = '/api'

export async function apiRequest(path, options = {}) {
  const res = await fetch(`${API_BASE}${path}`, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  })
  const data = await res.json().catch(() => ({}))
  if (!res.ok) {
    throw new Error(data?.details || data?.error || 'API error')
  }
  return data
}

export async function apiListProjects() {
  const data = await apiRequest('/projects')
  return data.projects || []
}

export async function apiGetLastProject() {
  const data = await apiRequest('/last-project')
  return data.name || ''
}

export async function apiSaveLastProject(name) {
  await apiRequest('/last-project', {
    method: 'PUT',
    body: JSON.stringify({ name }),
  })
}

export async function apiCreateProject(name) {
  await apiRequest('/projects', { method: 'POST', body: JSON.stringify({ name }) })
}

export async function apiGetProject(name) {
  return apiRequest(`/project/${encodeURIComponent(name)}`)
}

export async function apiSaveBlock(name, payload) {
  await apiRequest(`/project/${encodeURIComponent(name)}/block`, {
    method: 'PUT',
    body: JSON.stringify(payload),
  })
}

export async function apiSaveSettings(name, payload) {
  await apiRequest(`/project/${encodeURIComponent(name)}/settings`, {
    method: 'PUT',
    body: JSON.stringify(payload),
  })
}

export async function apiSaveLetters(name, payload) {
  await apiRequest(`/project/${encodeURIComponent(name)}/letters`, {
    method: 'PUT',
    body: JSON.stringify(payload),
  })
}

export async function apiGetLetter(name, id) {
  return apiRequest(`/project/${encodeURIComponent(name)}/letter/${encodeURIComponent(id)}`)
}

export async function apiSaveLetter(name, payload) {
  await apiRequest(`/project/${encodeURIComponent(name)}/letter`, {
    method: 'PUT',
    body: JSON.stringify(payload),
  })
}

export async function apiDeleteLetter(name, id) {
  await apiRequest(`/project/${encodeURIComponent(name)}/letter/${encodeURIComponent(id)}`, {
    method: 'DELETE',
  })
}

export async function apiGetLetterHistory(name, id) {
  return apiRequest(`/project/${encodeURIComponent(name)}/letter/${encodeURIComponent(id)}/history`)
}

export async function apiAppendLetterHistory(name, id, snapshot) {
  await apiRequest(`/project/${encodeURIComponent(name)}/letter/${encodeURIComponent(id)}/history`, {
    method: 'PUT',
    body: JSON.stringify({ snapshot }),
  })
}

export async function apiSaveDraft(name, payload) {
  await apiRequest(`/project/${encodeURIComponent(name)}/draft`, {
    method: 'PUT',
    body: JSON.stringify(payload),
  })
}

export async function apiSavePresets(name, payload) {
  await apiRequest(`/project/${encodeURIComponent(name)}/presets`, {
    method: 'PUT',
    body: JSON.stringify(payload),
  })
}

export async function apiSaveNotes(name, payload) {
  await apiRequest(`/project/${encodeURIComponent(name)}/notes`, {
    method: 'PUT',
    body: JSON.stringify(payload),
  })
}

export async function apiGetNote(name, id) {
  return apiRequest(`/project/${encodeURIComponent(name)}/note/${encodeURIComponent(id)}`)
}

export async function apiSaveNote(name, payload) {
  await apiRequest(`/project/${encodeURIComponent(name)}/note`, {
    method: 'PUT',
    body: JSON.stringify(payload),
  })
}

export async function apiDeleteNote(name, id) {
  await apiRequest(`/project/${encodeURIComponent(name)}/note/${encodeURIComponent(id)}`, {
    method: 'DELETE',
  })
}

export async function apiRenderEmail(name, payload) {
  return apiRequest(`/project/${encodeURIComponent(name)}/render-email`, {
    method: 'POST',
    body: JSON.stringify(payload),
  })
}

export function apiGetConfig() { return apiRequest('/config') }
export function apiSaveConfig(payload) { return apiRequest('/config', { method: 'PUT', body: JSON.stringify(payload) }) }
export function apiGetSheetsAuthStatus() { return apiRequest('/sheets/auth-status') }
export function apiReadSheet(spreadsheetId, sheetName) {
  return apiRequest(`/sheets/read?spreadsheetId=${encodeURIComponent(spreadsheetId)}&sheetName=${encodeURIComponent(sheetName)}`)
}
export function apiWriteSheetCell(spreadsheetId, sheetName, col, row, value) {
  return apiRequest('/sheets/write', { method: 'POST', body: JSON.stringify({ spreadsheetId, sheetName, col, row, value }) })
}
export function apiUploadImage(imageData, fileName, projectName) {
  return apiRequest('/upload-image', { method: 'POST', body: JSON.stringify({ imageData, fileName, projectName }) })
}
export function apiFeedRefresh(projectName) {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/feed-refresh`, { method: 'POST' })
}
export function apiFeedLookup(projectName, ids) {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/feed-lookup`, {
    method: 'POST', body: JSON.stringify({ ids }),
  })
}
export function apiFeedSuggest(projectName, productId, excludeIds = [], search = '') {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/feed-suggest`, {
    method: 'POST', body: JSON.stringify({ productId, excludeIds, search }),
  })
}
export function apiCheckLinks(urls) {
  return apiRequest('/check-links', { method: 'POST', body: JSON.stringify({ urls }) })
}
export function apiFtpTest(projectName) {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/ftp/test`, { method: 'POST' })
}
export function apiFtpUpload(projectName, { imageData, fileName, folder }) {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/ftp/upload`, {
    method: 'POST', body: JSON.stringify({ imageData, fileName, folder }),
  })
}
export function apiFtpList(projectName, folder) {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/ftp/list`, {
    method: 'POST', body: JSON.stringify({ folder }),
  })
}
export function apiGetStats(projectName) {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/stats`)
}
export function apiSaveStatEntry(projectName, entry) {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/stats`, {
    method: 'POST', body: JSON.stringify({ entry }),
  })
}
export function apiGetAllStats() {
  return apiRequest('/stats')
}
// Auth
export function apiLogin(login, password) {
  return apiRequest('/auth/login', { method: 'POST', body: JSON.stringify({ login, password }) })
}
export function apiLogout() {
  return apiRequest('/auth/logout', { method: 'POST' })
}
export async function apiGetMe() {
  try {
    return await apiRequest('/auth/me')
  } catch {
    return null
  }
}
export function apiSavePreferences(prefs) {
  return apiRequest('/auth/preferences', { method: 'PUT', body: JSON.stringify(prefs) })
}
export function apiAutoAssemble(projectName, type, target, productType, priceMin, priceMax, excludeMaterials, layout, excludeIds, anchorIds) {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/auto-assemble`, {
    method: 'POST',
    body: JSON.stringify({ type, target, productType, priceMin, priceMax, excludeMaterials, layout, excludeIds, anchorIds }),
  })
}
// Admin
export function apiAdminGetUsers() {
  return apiRequest('/admin/users')
}
export function apiAdminCreateUser(data) {
  return apiRequest('/admin/users', { method: 'POST', body: JSON.stringify(data) })
}
export function apiAdminUpdateUser(id, data) {
  return apiRequest(`/admin/users/${encodeURIComponent(id)}`, { method: 'PUT', body: JSON.stringify(data) })
}
export function apiAdminDeleteUser(id) {
  return apiRequest(`/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' })
}
export function apiAdminGetLogs({ user, project, action, from, to, page, limit } = {}) {
  const params = new URLSearchParams()
  if (user) params.set('user', user)
  if (project) params.set('project', project)
  if (action) params.set('action', action)
  if (from) params.set('from', from)
  if (to) params.set('to', to)
  if (page) params.set('page', page)
  if (limit) params.set('limit', limit)
  return apiRequest(`/admin/logs?${params}`)
}
