"use client";

import { NEXT_PUBLIC_API_URL } from "@/config/api";
import { MissingStockTakeSectionIssuesResponse, WarehouseResult } from "./index";

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

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

  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, "") || "warehouse_qrcode.pdf";
  
  const blob = await response.blob();
  const arrayBuffer = await blob.arrayBuffer();
  const blobValue = new Uint8Array(arrayBuffer);

  return { blobValue, filename };
};

export interface PrintWarehouseQrCodeRequest {
  warehouseIds: number[];
  printerId: number;
  printQty?: number;
}

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

  const response = await fetch(`${NEXT_PUBLIC_API_URL}/warehouse/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}`);
  }
};

export const fetchWarehouseListClient = async (): Promise<WarehouseResult[]> => {
  const token = localStorage.getItem("accessToken");
  
  const response = await fetch(`${NEXT_PUBLIC_API_URL}/warehouse`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      ...(token && { Authorization: `Bearer ${token}` }),
    },
  });

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

  return response.json();
};

export const fetchMissingStockTakeSectionIssues = async (
  limit = 50,
): Promise<MissingStockTakeSectionIssuesResponse> => {
  const token = localStorage.getItem("accessToken");
  const params = new URLSearchParams({ limit: String(limit) });
  const response = await fetch(
    `${NEXT_PUBLIC_API_URL}/warehouse/missingStockTakeSectionIssues?${params.toString()}`,
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        ...(token && { Authorization: `Bearer ${token}` }),
      },
    },
  );

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error("Unauthorized: Please log in again");
    }
    throw new Error(
      `Failed to fetch missing stock take section issues: ${response.status} ${response.statusText}`,
    );
  }

  return response.json();
};