import { apiFetch, buildApiUrl, getStoredToken } from "./http";
import type { MonthlyPayrollDetailResponse, MonthlyPayrollRun } from "./types";

export function listMonthlyRuns(month?: string): Promise<MonthlyPayrollRun[]> {
  const query = month ? `?month=${encodeURIComponent(month)}` : "";
  return apiFetch<MonthlyPayrollRun[]>(`/api/payroll/monthly/runs${query}`);
}

export function getMonthlyRun(runId: number): Promise<MonthlyPayrollDetailResponse> {
  return apiFetch<MonthlyPayrollDetailResponse>(`/api/payroll/monthly/runs/${runId}`);
}

export function calculateMonthlyFromExcel(
  file: File,
  salaryMonth: string,
  exportExcel = true,
): Promise<MonthlyPayrollDetailResponse> {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("salary_month", salaryMonth);
  formData.append("export_excel", String(exportExcel));
  return apiFetch<MonthlyPayrollDetailResponse>("/api/payroll/monthly/excel", {
    method: "POST",
    body: formData,
  });
}

export function calculateMonthlyFromDingTalk(
  salaryMonth: string,
  exportExcel = true,
): Promise<MonthlyPayrollDetailResponse> {
  return apiFetch<MonthlyPayrollDetailResponse>("/api/payroll/monthly/dingtalk", {
    method: "POST",
    body: JSON.stringify({
      salary_month: salaryMonth,
      source_type: "dingtalk",
      export_excel: exportExcel,
    }),
  });
}

export function recalculateMonthlyRun(runId: number): Promise<MonthlyPayrollDetailResponse> {
  return apiFetch<MonthlyPayrollDetailResponse>(`/api/payroll/monthly/runs/${runId}/recalculate`, {
    method: "POST",
  });
}

export function lockMonthlyRun(runId: number): Promise<MonthlyPayrollRun> {
  return apiFetch<MonthlyPayrollRun>(`/api/payroll/monthly/runs/${runId}/lock`, {
    method: "POST",
  });
}

export async function exportMonthlyRun(runId: number): Promise<void> {
  const headers = new Headers();
  const token = getStoredToken();
  if (token) {
    headers.set("Authorization", `Bearer ${token}`);
  }

  const response = await fetch(buildApiUrl(`/api/payroll/monthly/runs/${runId}/export`), { headers });
  if (!response.ok) {
    throw new Error("月度工资表导出失败");
  }

  const blob = await response.blob();
  const objectUrl = URL.createObjectURL(blob);
  const anchor = document.createElement("a");
  anchor.href = objectUrl;
  anchor.download = `月度工资核算-${runId}.xlsx`;
  document.body.appendChild(anchor);
  anchor.click();
  anchor.remove();
  URL.revokeObjectURL(objectUrl);
}
