import { apiClient } from './client';
import type {
  CasesFilterOptions,
  AssignableTaskStaff,
  LabCaseDetail,
  ListLabCasesParams,
  PaginatedLabCases,
} from '@/types/cases';

export const casesApi = {
  list: async (
    params: ListLabCasesParams = {},
  ): Promise<{ success: boolean; data: PaginatedLabCases }> => {
    const response = await apiClient.get('/cases', { params });
    return response.data;
  },

  getOne: async (id: string): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.get(`/cases/${id}`);
    return response.data;
  },

  listFilterOptions: async (): Promise<{ success: boolean; data: CasesFilterOptions }> => {
    const response = await apiClient.get('/cases/filter-options');
    return response.data;
  },

  listAssignableStaff: async (): Promise<{ success: boolean; data: AssignableTaskStaff[] }> => {
    const response = await apiClient.get('/cases/assignable-staff');
    return response.data;
  },

  assignTask: async (
    caseId: string,
    taskId: string,
    assigneeUserId: string | null,
  ): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.patch(`/cases/${caseId}/tasks/${taskId}/assign`, {
      assigneeUserId,
    });
    return response.data;
  },

  setCaseImportant: async (
    caseId: string,
    isImportant: boolean,
  ): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.patch(`/cases/${caseId}/important`, { isImportant });
    return response.data;
  },

  setCaseExternalCode: async (
    caseId: string,
    externalCode: string | null,
  ): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.patch(`/cases/${caseId}/external-code`, { externalCode });
    return response.data;
  },

  getAttachmentFileBlob: async (caseId: string, attachmentId: string): Promise<Blob> => {
    const response = await apiClient.get(`/cases/${caseId}/attachments/${attachmentId}/file`, {
      responseType: 'blob',
      timeout: 120_000,
    });
    return response.data;
  },
};
