import { apiClient } from '@/lib/api-client';
import type {
  CertificatesResponse,
  TrainingRecordCourseOption,
  TrainingRecordByIdResponse,
  TrainingRecordFilters,
  TrainingRecordFormOption,
  TrainingRecordImportResponse,
  TrainingRecordMutationPayload,
  TrainingRecordReviewPayload,
  TrainingRecordsResponse
} from './types';

export async function getTrainingRecords(
  filters: TrainingRecordFilters
): Promise<TrainingRecordsResponse> {
  const searchParams = new URLSearchParams();

  if (filters.page) searchParams.set('page', String(filters.page));
  if (filters.limit) searchParams.set('limit', String(filters.limit));
  if (filters.search) searchParams.set('search', filters.search);
  if (filters.statuses && filters.statuses !== 'all') searchParams.set('statuses', filters.statuses);
  if (filters.types && filters.types !== 'all') searchParams.set('types', filters.types);
  if (filters.year) searchParams.set('year', filters.year);
  if (filters.company) searchParams.set('company', filters.company);
  if (filters.department) searchParams.set('department', filters.department);
  if (filters.sort) searchParams.set('sort', filters.sort);

  return apiClient<TrainingRecordsResponse>(`/training-records?${searchParams.toString()}`);
}

export async function getTrainingRecordById(id: number): Promise<TrainingRecordByIdResponse> {
  return apiClient<TrainingRecordByIdResponse>(`/training-records/${id}`);
}

export async function createTrainingRecord(data: TrainingRecordMutationPayload) {
  return apiClient<TrainingRecordByIdResponse>('/training-records', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function updateTrainingRecord(id: number, data: TrainingRecordMutationPayload) {
  return apiClient<TrainingRecordByIdResponse>(`/training-records/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function deleteTrainingRecord(id: number) {
  return apiClient<{ success: boolean; message: string }>(`/training-records/${id}`, {
    method: 'DELETE'
  });
}

export async function reviewTrainingRecord(
  id: number,
  data: TrainingRecordReviewPayload
) {
  return apiClient<TrainingRecordByIdResponse>(`/training-records/${id}/review`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function getCertificates(trainingRecordId: number): Promise<CertificatesResponse> {
  return apiClient<CertificatesResponse>(`/training-records/${trainingRecordId}/certificates`);
}

export async function uploadCertificates(trainingRecordId: number, files: File[]) {
  const formData = new FormData();

  for (const file of files) {
    formData.append('files', file);
  }

  return apiClient<CertificatesResponse>(`/training-records/${trainingRecordId}/certificates`, {
    method: 'POST',
    body: formData
  });
}

export async function deleteCertificate(trainingRecordId: number, certificateId: number) {
  return apiClient<{ success: boolean; message: string }>(
    `/training-records/${trainingRecordId}/certificates/${certificateId}`,
    {
      method: 'DELETE'
    }
  );
}

export async function getUserOptions(): Promise<TrainingRecordFormOption[]> {
  const response = await apiClient<{
    employees: Array<{ value: string; label: string }>;
  }>('/employees?mode=options');

  return response.employees;
}

export async function getTrainingRecordCourseOptions(
  search?: string
): Promise<TrainingRecordCourseOption[]> {
  const searchParams = new URLSearchParams({
    page: '1',
    limit: '50',
    statuses: 'active'
  });

  if (search?.trim()) {
    searchParams.set('search', search.trim());
  }

  const response = await apiClient<{
    courses: TrainingRecordCourseOption[];
  }>(`/courses?${searchParams.toString()}`);

  return response.courses;
}

export async function importTrainingRecords(file: File) {
  const formData = new FormData();
  formData.append('file', file);

  return apiClient<TrainingRecordImportResponse>('/training-records/import', {
    method: 'POST',
    body: formData
  });
}
