import axios from 'axios';

const api = axios.create({
  baseURL: '/api',
  headers: { 'Content-Type': 'application/json' },
  timeout: 10000,
});

// Response interceptor — normalize errors
api.interceptors.response.use(
  (res) => res,
  (err) => {
    const message =
      err.response?.data?.error ||
      err.response?.data?.message ||
      err.message ||
      'An unexpected error occurred';
    const details = err.response?.data?.details || null;
    return Promise.reject({ message, details, status: err.response?.status });
  }
);

export default api;

// ── Experiments ────────────────────────────────────────────────────────────────
export const experimentsApi = {
  list: () => api.get('/experiments').then((r) => r.data),
  get: (id) => api.get(`/experiments/${id}`).then((r) => r.data),
  create: (data) => api.post('/experiments', data).then((r) => r.data),
  update: (id, data) => api.put(`/experiments/${id}`, data).then((r) => r.data),
  delete: (id) => api.delete(`/experiments/${id}`),
  getTemplate: (id) => api.get(`/experiments/${id}/template`).then((r) => r.data),
  updateTemplate: (id, template) => api.put(`/experiments/${id}/template`, template).then((r) => r.data),
  getSubjectTemplate: (id) => api.get(`/experiments/${id}/subject-template`).then((r) => r.data),
  updateSubjectTemplate: (id, template) => api.put(`/experiments/${id}/subject-template`, template).then((r) => r.data),
  savePlotConfig: (id, config) => api.put(`/experiments/${id}/plot-config`, config).then((r) => r.data),
  // opts: { date?: string, analysisOnly?: boolean }
  getDailyStatuses: (id, opts) => {
    const params = typeof opts === 'string' ? { date: opts } : (opts ?? {});
    return api.get(`/experiments/${id}/daily-statuses`, { params }).then((r) => r.data);
  },
  getDayStatuses: (id, date) => api.get(`/experiments/${id}/daily-statuses`, { params: { date } }).then((r) => r.data),
  getCalendar: (id, field) => api.get(`/experiments/${id}/calendar`, { params: { field } }).then((r) => r.data),
};

// ── Animals ───────────────────────────────────────────────────────────────────
export const animalsApi = {
  list: (experimentId) =>
    api.get('/animals', { params: { experimentId } }).then((r) => r.data),
  get: (id) => api.get(`/animals/${id}`).then((r) => r.data),
  create: (data) => api.post('/animals', data).then((r) => r.data),
  update: (id, data) => api.put(`/animals/${id}`, data).then((r) => r.data),
  delete: (id) => api.delete(`/animals/${id}`),
  updateCsvConfig: (id, config) =>
    api.patch(`/animals/${id}/csv-config`, config).then((r) => r.data),
};

// ── Daily Statuses ─────────────────────────────────────────────────────────────
export const dailyStatusesApi = {
  list: (animalId) =>
    api.get('/daily-statuses', { params: { animalId } }).then((r) => r.data),
  get: (id) => api.get(`/daily-statuses/${id}`).then((r) => r.data),
  create: (data) => api.post('/daily-statuses', data).then((r) => r.data),
  update: (id, data) => api.put(`/daily-statuses/${id}`, data).then((r) => r.data),
  delete: (id) => api.delete(`/daily-statuses/${id}`),
  updateAnalysisSummary: (id, data) => api.put(`/daily-statuses/${id}/analysis-summary`, data).then((r) => r.data),
};

// ── Audit Logs ────────────────────────────────────────────────────────────────
export const auditLogsApi = {
  list: (params) => api.get('/audit-logs', { params }).then((r) => r.data),
};

// ── System ────────────────────────────────────────────────────────────────────
export const systemApi = {
  info: () => api.get('/info').then((r) => r.data),
};

// ── Session Files ─────────────────────────────────────────────────────────────
export const sessionFilesApi = {
  list:   (statusId) => api.get(`/daily-statuses/${statusId}/files`).then((r) => r.data),
  create: (statusId, files) => api.post(`/daily-statuses/${statusId}/files`, files).then((r) => r.data),
  delete: (id) => api.delete(`/session-files/${id}`),
};

// ── Analyses ──────────────────────────────────────────────────────────────────
export const analysesApi = {
  listForStatus: (statusId) => api.get(`/daily-statuses/${statusId}/analyses`).then((r) => r.data),
  create: (statusId, data) => api.post(`/daily-statuses/${statusId}/analyses`, data).then((r) => r.data),
  get: (id) => api.get(`/analyses/${id}`).then((r) => r.data),
  delete: (id) => api.delete(`/analyses/${id}`),
};
