import { ApiError, apiFetch, buildApiUrl, getStoredToken } from "./http";
import type {
  DingTalkPayrollRequest,
  PayrollResponse,
  RecentPayrollJob,
} from "./types";

const RECENT_JOBS_KEY = "financial-system-recent-payroll-jobs";

export function calculateFromExcel(
  file: File,
  exportExcel: boolean,
  configPath?: string,
): Promise<PayrollResponse> {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("export_excel", String(exportExcel));
  if (configPath) {
    formData.append("config_path", configPath);
  }

  return apiFetch<PayrollResponse>("/api/payroll/excel", {
    method: "POST",
    body: formData,
  });
}

export function calculateFromDingTalk(payload: DingTalkPayrollRequest): Promise<PayrollResponse> {
  return apiFetch<PayrollResponse>("/api/payroll/dingtalk/realtime", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export function getDownloadUrl(downloadUrl: string | null, outputFile?: string | null): string {
  if (downloadUrl) {
    return buildApiUrl(downloadUrl);
  }

  const filename = outputFile?.split(/[\\/]/).pop();
  return filename ? buildApiUrl(`/api/payroll/download/${encodeURIComponent(filename)}`) : "";
}

export async function downloadPayrollFile(downloadUrl: string | null, outputFile?: string | null): Promise<void> {
  const url = getDownloadUrl(downloadUrl, outputFile);
  if (!url) {
    throw new Error("没有可下载的结果文件");
  }

  const headers = new Headers();
  const token = getStoredToken();
  if (token) {
    headers.set("Authorization", `Bearer ${token}`);
  }

  const response = await fetch(url, { headers });
  if (!response.ok) {
    throw new ApiError("下载失败，请确认文件仍然存在", response.status);
  }

  const blob = await response.blob();
  const objectUrl = URL.createObjectURL(blob);
  const filename = outputFile?.split(/[\\/]/).pop() || "工资计算结果.xlsx";
  const anchor = document.createElement("a");
  anchor.href = objectUrl;
  anchor.download = filename;
  document.body.appendChild(anchor);
  anchor.click();
  anchor.remove();
  URL.revokeObjectURL(objectUrl);
}

export function readRecentJobs(): RecentPayrollJob[] {
  try {
    const raw = localStorage.getItem(RECENT_JOBS_KEY);
    return raw ? (JSON.parse(raw) as RecentPayrollJob[]) : [];
  } catch {
    return [];
  }
}

export function saveRecentJob(sourceType: string, response: PayrollResponse): void {
  const nextJob: RecentPayrollJob = {
    job_id: response.job_id,
    source_type: sourceType,
    employee_count: response.employee_count,
    output_file: response.output_file,
    download_url: response.download_url,
    created_at: new Date().toISOString(),
  };
  const jobs = [nextJob, ...readRecentJobs().filter((item) => item.job_id !== response.job_id)].slice(0, 12);
  localStorage.setItem(RECENT_JOBS_KEY, JSON.stringify(jobs));
}
