"use client";

import axiosInstance from "@/app/(main)/axios/axiosInstance";
import { NEXT_PUBLIC_API_URL } from "@/config/api";
import type {
    BomFormatCheckResponse,
    BomUploadResponse,
    ImportBomItemPayload,
    BomCombo,
    BomDetailResponse,
    EditBomRequest,
} from "./index";

export async function uploadBomFiles(
    files: File[]
): Promise<BomUploadResponse> {
    const formData = new FormData();
    files.forEach((f) => formData.append("files", f, f.name));
    const response = await axiosInstance.post<BomUploadResponse>(
        `${NEXT_PUBLIC_API_URL}/bom/import-bom/upload`,
        formData,
        {
            transformRequest: [
                (data: unknown, headers?: Record<string, unknown>) => {
                    if (data instanceof FormData && headers && "Content-Type" in headers) {
                        delete headers["Content-Type"];
                    }
                    return data;
                },
            ],
        }
    );
    return response.data;
}

export async function checkBomFormat(
    batchId: string
): Promise<BomFormatCheckResponse> {
    const response = await axiosInstance.post<BomFormatCheckResponse>(
        `${NEXT_PUBLIC_API_URL}/bom/import-bom/format-check`,
        { batchId }
    );
    return response.data;
}
export async function downloadBomFormatIssueLog(
    batchId: string,
    issueLogFileId: string
  ): Promise<Blob> {
    const response = await axiosInstance.get(
      `${NEXT_PUBLIC_API_URL}/bom/import-bom/format-issue-log`,
      {
        params: { batchId, issueLogFileId },
        responseType: "blob",
      }
    );
    return response.data as Blob;
  }
export async function importBom(
    batchId: string,
    items: ImportBomItemPayload[]
): Promise<Blob> {
    const response = await axiosInstance.post(
        `${NEXT_PUBLIC_API_URL}/bom/import-bom`,
        { batchId, items },
        { responseType: "blob" }
    );
    return response.data as Blob;
}
import type { BomScoreResult } from "./index";

export const fetchBomScoresClient = async (): Promise<BomScoreResult[]> => {
  const response = await axiosInstance.get<BomScoreResult[]>(
    `${NEXT_PUBLIC_API_URL}/bom/scores`,
  );
  return response.data;
};

export async function fetchBomComboClient(): Promise<BomCombo[]> {
    const response = await axiosInstance.get<BomCombo[]>(
      `${NEXT_PUBLIC_API_URL}/bom/combo`
    );
    return response.data;
  }

  
  export async function fetchBomDetailClient(id: number): Promise<BomDetailResponse> {
    const response = await axiosInstance.get<BomDetailResponse>(
      `${NEXT_PUBLIC_API_URL}/bom/${id}/detail`
    );
    return response.data;
  }

  export async function editBomClient(
    id: number,
    request: EditBomRequest,
  ): Promise<BomDetailResponse> {
    const response = await axiosInstance.put<BomDetailResponse>(
      `${NEXT_PUBLIC_API_URL}/bom/${id}`,
      request,
    );
    return response.data;
  }
  export type BomExcelCheckProgress = {
    batchId: string;
    totalFiles: number;
    processedFiles: number;
    currentFileName: string | null;
    lastUpdateTime: number;
  };
  
  export async function getBomFormatProgress(
    batchId: string
  ): Promise<BomExcelCheckProgress> {
    const response = await axiosInstance.get<BomExcelCheckProgress>(
      `${NEXT_PUBLIC_API_URL}/bom/import-bom/format-check/progress`,
      { params: { batchId } }
    );
    return response.data;
  }

/** Master `equipment` rows for BOM process editor (description/name → code). */
export type EquipmentMasterRow = {
  code: string;
  name: string;
  description: string;
};

/** Master `process` rows for BOM process editor (dropdown by code). */
export type ProcessMasterRow = {
  code: string;
  name: string;
};

export async function fetchAllEquipmentsMasterClient(): Promise<
  EquipmentMasterRow[]
> {
  const response = await axiosInstance.get<unknown[]>(
    `${NEXT_PUBLIC_API_URL}/Equipment`,
  );
  const rows = Array.isArray(response.data) ? response.data : [];
  return rows.map((r: any) => ({
    code: String(r?.code ?? "").trim(),
    name: String(r?.name ?? "").trim(),
    description: String(r?.description ?? "").trim(),
  }));
}

export async function fetchAllProcessesMasterClient(): Promise<
  ProcessMasterRow[]
> {
  const response = await axiosInstance.get<unknown[]>(
    `${NEXT_PUBLIC_API_URL}/Process`,
  );
  const rows = Array.isArray(response.data) ? response.data : [];
  return rows.map((r: any) => ({
    code: String(r?.code ?? "").trim(),
    name: String(r?.name ?? "").trim(),
  }));
}