import { apiFetch } from "./http";
import type { EmployeeListResponse, EmployeeNoResponse, EmployeeRecord, EmployeeRequest } from "./types";

export function listEmployees(
  params: { keyword?: string; employee_keyword?: string; organization_keyword?: string; employment_status?: string } = {},
): Promise<EmployeeRecord[]> {
  const search = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && String(value).trim() !== "") {
      search.set(key, String(value));
    }
  });
  const query = search.toString();
  return apiFetch<EmployeeRecord[]>(`/api/employees${query ? `?${query}` : ""}`);
}

export function listEmployeePage(
  params: {
    page?: number;
    page_size?: number;
    keyword?: string;
    employee_keyword?: string;
    organization_keyword?: string;
    employment_status?: string;
  } = {},
): Promise<EmployeeListResponse> {
  const search = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && String(value).trim() !== "") {
      search.set(key, String(value));
    }
  });
  const query = search.toString();
  return apiFetch<EmployeeListResponse>(`/api/employees/page${query ? `?${query}` : ""}`);
}

export function getEmployee(employeeId: number): Promise<EmployeeRecord> {
  return apiFetch<EmployeeRecord>(`/api/employees/${employeeId}`);
}

export function previewNextEmployeeNo(): Promise<EmployeeNoResponse> {
  return apiFetch<EmployeeNoResponse>("/api/employees/next-no");
}

export function createEmployee(payload: EmployeeRequest): Promise<EmployeeRecord> {
  return apiFetch<EmployeeRecord>("/api/employees", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export function updateEmployee(employeeId: number, payload: EmployeeRequest): Promise<EmployeeRecord> {
  return apiFetch<EmployeeRecord>(`/api/employees/${employeeId}`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
}
