import { apiFetch } from "./http";
import type {
  CommissionImportResponse,
  CommissionListResponse,
  CommissionRecord,
  CommissionRecordRequest,
} from "./types";

export interface CommissionQuery {
  page?: number;
  page_size?: number;
  commission_month?: string;
  keyword?: string;
}

export function listCommissions(query: CommissionQuery): Promise<CommissionListResponse> {
  const params = new URLSearchParams();
  Object.entries(query).forEach(([key, value]) => {
    if (value !== undefined && value !== "") {
      params.set(key, String(value));
    }
  });
  return apiFetch<CommissionListResponse>(`/api/commissions?${params.toString()}`);
}

export function createCommission(request: CommissionRecordRequest): Promise<CommissionRecord> {
  return apiFetch<CommissionRecord>("/api/commissions", {
    method: "POST",
    body: JSON.stringify(request),
  });
}

export function updateCommission(id: number, request: CommissionRecordRequest): Promise<CommissionRecord> {
  return apiFetch<CommissionRecord>(`/api/commissions/${id}`, {
    method: "PUT",
    body: JSON.stringify(request),
  });
}

export function deleteCommission(id: number): Promise<{ message: string }> {
  return apiFetch<{ message: string }>(`/api/commissions/${id}`, {
    method: "DELETE",
  });
}

export function importCommissions(file: File): Promise<CommissionImportResponse> {
  const form = new FormData();
  form.append("file", file);
  return apiFetch<CommissionImportResponse>("/api/commissions/import", {
    method: "POST",
    body: form,
  });
}
