import { adminHttp, adminRequest } from "@/lib/admin-http";
import { withAdminAuthHeader } from "@/lib/admin-auth";
import { withAdminLocaleHeaders } from "@/lib/admin-locale";


import type {
  AdminReportJobCreatePayload,
  AdminReportJobCreateResult,
  AdminReportJobListData,
  AdminReportJobRow,
} from "@/types/api/admin-report-jobs";

const A = `/admin/report-jobs`;

export async function getAdminReportJobs(params?: {
  page?: number;
  per_page?: number;
  report_type?: string;
}): Promise<AdminReportJobListData> {
  return adminRequest.get<AdminReportJobListData>(A, { params });
}

export async function postAdminReportJob(
  payload: AdminReportJobCreatePayload,
): Promise<AdminReportJobCreateResult> {
  return adminRequest.post<AdminReportJobCreateResult>(A, payload);
}

export async function getAdminReportJob(id: number): Promise<AdminReportJobRow> {
  return adminRequest.get<AdminReportJobRow>(`${A}/${id}`);
}

function filenameFromContentDisposition(header: string | undefined): string | null {
  if (!header) {
    return null;
  }
  const utf8 = /filename\*=UTF-8''([^;]+)/i.exec(header);
  if (utf8?.[1]) {
    try {
      return decodeURIComponent(utf8[1].trim());
    } catch {
      return utf8[1].trim();
    }
  }
  const plain = /filename="?([^";]+)"?/i.exec(header);
  return plain?.[1]?.trim() ?? null;
}

export async function downloadAdminReportJob(
  id: number,
): Promise<{ blob: Blob; filename: string | null }> {
  const res = await adminHttp.request<Blob>(
    withAdminAuthHeader(
      withAdminLocaleHeaders({
        url: `${A}/${id}/download`,
        method: "GET",
        responseType: "blob",
      }),
    ),
  );
  const filename = filenameFromContentDisposition(
    typeof res.headers["content-disposition"] === "string" ? res.headers["content-disposition"] : undefined,
  );
  return { blob: res.data, filename };
}
