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
}

// Single-project: always vipavenue
export const PROJECT_NAME = 'vipavenue'

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) }) }
// Yonote API
export function apiGetYonoteStatus() { return apiRequest('/yonote/status') }
export function apiYonoteListDatabases() { return apiRequest('/yonote/databases') }
export function apiYonoteGetProperties(databaseId) {
  return apiRequest(`/yonote/database/${encodeURIComponent(databaseId)}/properties`)
}
export function apiYonoteGetRows(databaseId) {
  return apiRequest(`/yonote/database/${encodeURIComponent(databaseId)}/rows`)
}
export function apiYonoteUpdateRow(rowId, values) {
  return apiRequest('/yonote/row/update', { method: 'POST', body: JSON.stringify({ rowId, values }) })
}
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 apiFtpDelete(projectName, { folder, fileName }) {
  return apiRequest(`/project/${encodeURIComponent(projectName)}/ftp/delete`, {
    method: 'POST', body: JSON.stringify({ folder, fileName }),
  })
}
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 function apiGetMe() {
  return fetch('/api/auth/me', { headers: { 'Content-Type': 'application/json' } })
    .then(r => r.ok ? r.json() : null)
    .catch(() => null)
}
export function apiSavePreferences(prefs) {
  return apiRequest('/auth/preferences', { method: 'PUT', body: JSON.stringify(prefs) })
}
// 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 apiReadPartsFile(filePath) {
  return apiRequest(`/parts-file-read?path=${encodeURIComponent(filePath)}`)
}
export function apiWritePartsFile(filePath, content) {
  return apiRequest('/parts-file-write', { method: 'POST', body: JSON.stringify({ path: filePath, content }) })
}
