import { apiClient } from '@/lib/api-client';
import type {
  DocumentLibraryDetailResponse,
  DocumentLibraryFilters,
  DocumentLibraryListResponse,
  DocumentLibraryMutationPayload,
  DocumentLibraryVersionActionResponse,
  DocumentLibraryVersionUploadPayload,
  MutationSuccessResponse
} from './types';

const BASE_PATH = '/crm/settings/document-library';

async function uploadFormData<T>(endpoint: string, formData: FormData): Promise<T> {
  const response = await fetch(`/api${endpoint}`, {
    method: 'POST',
    body: formData
  });

  if (!response.ok) {
    const payload = (await response.json().catch(() => null)) as
      | { message?: string }
      | null;
    throw new Error(payload?.message || `API error: ${response.status}`);
  }

  return response.json() as Promise<T>;
}

export async function getDocumentLibraries(filters: DocumentLibraryFilters = {}) {
  const searchParams = new URLSearchParams();

  if (filters.documentType) searchParams.set('documentType', filters.documentType);
  if (filters.brand) searchParams.set('brand', filters.brand);
  if (filters.language) searchParams.set('language', filters.language);
  if (filters.productType) searchParams.set('productType', filters.productType);
  if (filters.isActive) searchParams.set('isActive', filters.isActive);

  const query = searchParams.toString();
  return apiClient<DocumentLibraryListResponse>(`${BASE_PATH}${query ? `?${query}` : ''}`);
}

export async function getDocumentLibraryById(id: string) {
  return apiClient<DocumentLibraryDetailResponse>(`${BASE_PATH}/${id}`);
}

export async function createDocumentLibrary(values: DocumentLibraryMutationPayload) {
  return apiClient<MutationSuccessResponse>(BASE_PATH, {
    method: 'POST',
    body: JSON.stringify(values)
  });
}

export async function updateDocumentLibrary(
  id: string,
  values: Partial<DocumentLibraryMutationPayload>
) {
  return apiClient<MutationSuccessResponse>(`${BASE_PATH}/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(values)
  });
}

export async function uploadDocumentLibraryVersion(
  libraryId: string,
  payload: DocumentLibraryVersionUploadPayload
) {
  const formData = new FormData();
  formData.set('version', payload.version);
  formData.set('file', payload.file);
  return uploadFormData<DocumentLibraryVersionActionResponse>(
    `${BASE_PATH}/${libraryId}/versions`,
    formData
  );
}

export async function publishDocumentLibraryVersion(versionId: string) {
  return apiClient<DocumentLibraryVersionActionResponse>(
    `${BASE_PATH}/versions/${versionId}/publish`,
    { method: 'POST', body: JSON.stringify({}) }
  );
}

export async function activateDocumentLibraryVersion(versionId: string) {
  return apiClient<DocumentLibraryVersionActionResponse>(
    `${BASE_PATH}/versions/${versionId}/activate`,
    { method: 'POST', body: JSON.stringify({}) }
  );
}

export async function archiveDocumentLibraryVersion(versionId: string) {
  return apiClient<DocumentLibraryVersionActionResponse>(
    `${BASE_PATH}/versions/${versionId}/archive`,
    { method: 'POST', body: JSON.stringify({}) }
  );
}

export async function deleteDraftDocumentLibraryVersion(versionId: string) {
  return apiClient<DocumentLibraryVersionActionResponse>(
    `${BASE_PATH}/versions/${versionId}`,
    { method: 'DELETE' }
  );
}

export function getDocumentLibraryPreviewUrl(versionId: string) {
  return `/api${BASE_PATH}/versions/${versionId}/preview`;
}

export function getDocumentLibraryDownloadUrl(versionId: string) {
  return `/api${BASE_PATH}/versions/${versionId}/download`;
}

export function getActiveDocumentLibraryPreviewUrl(libraryId: string) {
  return `/api${BASE_PATH}/${libraryId}/preview`;
}

export function getActiveDocumentLibraryDownloadUrl(libraryId: string) {
  return `/api${BASE_PATH}/${libraryId}/download`;
}
