// ---------------------------------------------------------------------------
// Documents API client  (client-side)
// ---------------------------------------------------------------------------

import { apiFetch } from './client';

// ---------------------------------------------------------------------------
// Request / response shapes
// TODO: import from @/lib/types once the shared types package is finalised
// ---------------------------------------------------------------------------

export type DocumentType =
  | 'general'
  | 'warranty'
  | 'receipt'
  | 'contract'
  | 'insurance'
  | 'manual';

export interface CreateDocumentRequest {
  residence_id: number;
  title: string;
  description?: string;
  document_type?: DocumentType;
  file_url?: string;
  file_name?: string;
  file_size?: number;
  mime_type?: string;
  purchase_date?: string;
  expiry_date?: string;
  purchase_price?: number;
  vendor?: string;
  serial_number?: string;
  model_number?: string;
  task_id?: number;
  image_urls?: string[];
}

export interface UpdateDocumentRequest {
  title?: string;
  description?: string;
  document_type?: DocumentType;
  file_url?: string;
  file_name?: string;
  file_size?: number;
  mime_type?: string;
  purchase_date?: string;
  expiry_date?: string;
  purchase_price?: number;
  vendor?: string;
  serial_number?: string;
  model_number?: string;
  task_id?: number;
}

export interface DocumentResponse {
  id: number;
  residence_id: number;
  residence_name: string;
  title: string;
  description: string;
  document_type: DocumentType;
  file_url: string;
  file_name: string;
  file_size?: number;
  mime_type: string;
  purchase_date?: string;
  expiry_date?: string;
  purchase_price?: number;
  vendor: string;
  serial_number: string;
  model_number: string;
  is_active: boolean;
  task_id?: number;
  images: DocumentImageResponse[];
  created_by: DocumentUserResponse;
  created_at: string;
  updated_at: string;
}

export interface DocumentImageResponse {
  id: number;
  image_url: string;
  caption: string;
}

export interface DocumentUserResponse {
  id: number;
  username: string;
  first_name: string;
  last_name: string;
}

export interface DocumentActivateResponse {
  message: string;
  document: DocumentResponse;
}

export interface MessageResponse {
  message: string;
}

// ---------------------------------------------------------------------------
// Query filter parameters for list endpoint
// ---------------------------------------------------------------------------

export interface DocumentListParams {
  residence?: number;
  document_type?: DocumentType;
  is_active?: boolean;
  expiring_soon?: number; // days
  search?: string;
}

// ---------------------------------------------------------------------------
// API functions
// ---------------------------------------------------------------------------

/** List documents, optionally filtered. */
export function listDocuments(
  params?: DocumentListParams,
): Promise<DocumentResponse[]> {
  let queryString = '';
  if (params) {
    const searchParams = new URLSearchParams();
    if (params.residence != null)
      searchParams.set('residence', String(params.residence));
    if (params.document_type)
      searchParams.set('document_type', params.document_type);
    if (params.is_active != null)
      searchParams.set('is_active', String(params.is_active));
    if (params.expiring_soon != null)
      searchParams.set('expiring_soon', String(params.expiring_soon));
    if (params.search) searchParams.set('search', params.search);
    const qs = searchParams.toString();
    if (qs) queryString = `?${qs}`;
  }
  return apiFetch<DocumentResponse[]>(`/documents/${queryString}`);
}

/** List warranty documents. */
export function listWarranties(): Promise<DocumentResponse[]> {
  return apiFetch<DocumentResponse[]>('/documents/warranties/');
}

/** Get a single document by ID. */
export function getDocument(id: number): Promise<DocumentResponse> {
  return apiFetch<DocumentResponse>(`/documents/${id}/`);
}

/** Create a new document (JSON body, no file upload). */
export function createDocument(
  data: CreateDocumentRequest,
): Promise<DocumentResponse> {
  return apiFetch<DocumentResponse>('/documents/', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

/**
 * Create a document with file upload (multipart/form-data).
 * Use this when the user attaches a file to the document.
 */
export function createDocumentWithFile(
  data: Omit<CreateDocumentRequest, 'file_url' | 'file_name' | 'file_size' | 'mime_type'>,
  file: File,
): Promise<DocumentResponse> {
  const formData = new FormData();
  formData.append('residence_id', String(data.residence_id));
  formData.append('title', data.title);
  if (data.description) formData.append('description', data.description);
  if (data.document_type) formData.append('document_type', data.document_type);
  if (data.vendor) formData.append('vendor', data.vendor);
  if (data.serial_number) formData.append('serial_number', data.serial_number);
  if (data.model_number) formData.append('model_number', data.model_number);
  if (data.purchase_date) formData.append('purchase_date', data.purchase_date);
  if (data.expiry_date) formData.append('expiry_date', data.expiry_date);
  if (data.purchase_price != null)
    formData.append('purchase_price', String(data.purchase_price));
  if (data.task_id != null)
    formData.append('task_id', String(data.task_id));
  formData.append('file', file);

  return apiFetch<DocumentResponse>('/documents/', {
    method: 'POST',
    body: formData,
  });
}

/** Update an existing document. */
export function updateDocument(
  id: number,
  data: UpdateDocumentRequest,
): Promise<DocumentResponse> {
  return apiFetch<DocumentResponse>(`/documents/${id}/`, {
    method: 'PUT',
    body: JSON.stringify(data),
  });
}

/** Delete a document. */
export function deleteDocument(id: number): Promise<MessageResponse> {
  return apiFetch<MessageResponse>(`/documents/${id}/`, {
    method: 'DELETE',
  });
}

/** Activate a document. */
export function activateDocument(
  id: number,
): Promise<DocumentActivateResponse> {
  return apiFetch<DocumentActivateResponse>(`/documents/${id}/activate/`, {
    method: 'POST',
  });
}

/** Deactivate a document. */
export function deactivateDocument(
  id: number,
): Promise<DocumentActivateResponse> {
  return apiFetch<DocumentActivateResponse>(`/documents/${id}/deactivate/`, {
    method: 'POST',
  });
}

/** Upload an image to a document. */
export function uploadDocumentImage(
  documentId: number,
  image: File,
  caption?: string,
): Promise<DocumentImageResponse> {
  const formData = new FormData();
  formData.append('image', image);
  if (caption) formData.append('caption', caption);

  return apiFetch<DocumentImageResponse>(`/documents/${documentId}/images/`, {
    method: 'POST',
    body: formData,
  });
}

/** Delete an image from a document. */
export function deleteDocumentImage(
  documentId: number,
  imageId: number,
): Promise<DocumentResponse> {
  return apiFetch<DocumentResponse>(
    `/documents/${documentId}/images/${imageId}/`,
    { method: 'DELETE' },
  );
}
