"use client";

import { NEXT_PUBLIC_API_URL } from "@/config/api";
import { EquipmentDetailResult } from "./index";

export const exportEquipmentQrCode = async (equipmentDetailIds: number[]): Promise<{ blobValue: Uint8Array; filename: string }> => {

  const token = localStorage.getItem("accessToken");
  
  const response = await fetch(`${NEXT_PUBLIC_API_URL}/Equipment/export-qrcode`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(token && { Authorization: `Bearer ${token}` }),
    },
    body: JSON.stringify({ equipmentDetailIds }),
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error("Unauthorized: Please log in again");
    }
    throw new Error(`Failed to export QR code: ${response.status} ${response.statusText}`);
  }

  const filename = response.headers.get("Content-Disposition")?.split("filename=")[1]?.replace(/"/g, "") || "equipment_qrcode.pdf";
  
  const blob = await response.blob();
  const arrayBuffer = await blob.arrayBuffer();
  const blobValue = new Uint8Array(arrayBuffer);

  return { blobValue, filename };
};

export interface PrintEquipmentQrCodeRequest {
  equipmentDetailIds: number[];
  printerId: number;
  printQty?: number;
}

export const printEquipmentQrCode = async (data: PrintEquipmentQrCodeRequest): Promise<void> => {
  const token = localStorage.getItem("accessToken");

  const response = await fetch(`${NEXT_PUBLIC_API_URL}/Equipment/print-qrcode`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(token && { Authorization: `Bearer ${token}` }),
    },
    body: JSON.stringify(data),
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error("Unauthorized: Please log in again");
    }
    throw new Error(`Failed to print QR code: ${response.status} ${response.statusText}`);
  }
};
