/**
 * Import Session API Service
 *
 * Handles all API calls for import session persistence.
 */

import { apiFetch } from '@/utils/api';
import type {
  ImportSession,
  ImportSessionListItem,
  ImportSessionCreateRequest,
  ImportSessionUpdateRequest,
  ImportSessionAutosaveRequest,
} from '@/types/importSession';

const BASE_URL = '/api/import-sessions';

/**
 * Helper to handle API responses
 */
async function handleResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    const errorBody = await response.text();
    let errorMessage: string;
    try {
      const parsed = JSON.parse(errorBody);
      errorMessage = parsed.error || parsed.message || `HTTP ${response.status}`;
    } catch {
      errorMessage = errorBody || `HTTP ${response.status}`;
    }
    throw new Error(errorMessage);
  }
  return response.json();
}

/**
 * List all sessions for a user (named + unnamed)
 */
export async function listSessions(userId: number): Promise<ImportSessionListItem[]> {
  const response = await apiFetch(`${BASE_URL}?user_id=${userId}`);
  return handleResponse<ImportSessionListItem[]>(response);
}

/**
 * Get a specific session by ID (includes full data)
 */
export async function getSession(id: number): Promise<ImportSession> {
  const response = await apiFetch(`${BASE_URL}/${id}`);
  return handleResponse<ImportSession>(response);
}

/**
 * Create a new named session
 */
export async function createSession(data: ImportSessionCreateRequest): Promise<ImportSession> {
  const response = await apiFetch(BASE_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  return handleResponse<ImportSession>(response);
}

/**
 * Update an existing session by ID
 */
export async function updateSession(id: number, data: ImportSessionUpdateRequest): Promise<ImportSession> {
  const response = await apiFetch(`${BASE_URL}/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  return handleResponse<ImportSession>(response);
}

/**
 * Autosave - upsert the unnamed session for a user
 */
export async function autosaveSession(data: ImportSessionAutosaveRequest): Promise<ImportSession> {
  const response = await apiFetch(`${BASE_URL}/autosave`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  return handleResponse<ImportSession>(response);
}

/**
 * Delete a session by ID
 */
export async function deleteSession(id: number): Promise<void> {
  const response = await apiFetch(`${BASE_URL}/${id}`, {
    method: 'DELETE',
  });
  if (!response.ok) {
    const errorBody = await response.text();
    let errorMessage: string;
    try {
      const parsed = JSON.parse(errorBody);
      errorMessage = parsed.error || parsed.message || `HTTP ${response.status}`;
    } catch {
      errorMessage = errorBody || `HTTP ${response.status}`;
    }
    throw new Error(errorMessage);
  }
}

/**
 * Delete the unnamed/autosave session for a user
 */
export async function deleteAutosaveSession(userId: number): Promise<void> {
  const response = await apiFetch(`${BASE_URL}/autosave/${userId}`, {
    method: 'DELETE',
  });
  // 404 is ok - means no autosave existed
  if (!response.ok && response.status !== 404) {
    const errorBody = await response.text();
    let errorMessage: string;
    try {
      const parsed = JSON.parse(errorBody);
      errorMessage = parsed.error || parsed.message || `HTTP ${response.status}`;
    } catch {
      errorMessage = errorBody || `HTTP ${response.status}`;
    }
    throw new Error(errorMessage);
  }
}

/**
 * Convenience export for all API methods
 */
export const importSessionApi = {
  list: listSessions,
  get: getSession,
  create: createSession,
  update: updateSession,
  autosave: autosaveSession,
  delete: deleteSession,
  deleteAutosave: deleteAutosaveSession,
};
