import { serverFetchJson } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { cache } from "react";
import "server-only";

export interface UserResult {
  action: any;
  id: number;
  username: string;
  staffNo: number;
  name: string;
}

// export interface DetailedUser extends UserResult {
//     username: string;
//     password: string
// }

export interface UserDetail {
  data: UserResult;
  authIds: number[];
  groupIds: number[];
  auths: any[];
}

export type passwordRule = {
  min: number;
  max: number;
  number: boolean;
  upperEng: boolean;
  lowerEng: boolean;
  specialChar: boolean;
};

export interface EscalationCombo {
  id: number;
  value: number;
  label: string;
  name: string;
  title: string;
  department: string;
}

export const preloadUser = () => {
  fetchUser();
};

export const preloadUserDetail = (id: number) => {
  fetchUserDetail(id);
};

export const fetchUser = cache(async () => {
  return serverFetchJson<UserResult[]>(`${BASE_API_URL}/user`, {
    next: { tags: ["user"] },
  });
});

export const fetchUserDetail = cache(async (id: number) => {
  return serverFetchJson<UserResult[]>(`${BASE_API_URL}/user/${id}`, {
    next: { tags: ["user"] },
  });
});

export const fetchPwRules = cache(async () => {
  return serverFetchJson<passwordRule>(`${BASE_API_URL}/user/password-rule`, {
    next: { tags: ["pwRule"] },
  });
});

export const fetchEscalationCombo = cache(async () => {
  return serverFetchJson<EscalationCombo[]>(`${BASE_API_URL}/user/escalation-combo`, {
    next: { tags: ["escalationCombo"]}
  })
})


export const exportUserQrCode = async (userIds: number[]): Promise<{ blobValue: Uint8Array; filename: string }> => {
  const response = await fetch(`${BASE_API_URL}/user/export-qrcode`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ userIds }),
  });

  if (!response.ok) {
    throw new Error("Failed to export QR code");
  }

  const filename = response.headers.get("Content-Disposition")?.split("filename=")[1]?.replace(/"/g, "") || "user_qrcode.pdf";

  const blob = await response.blob();
  const arrayBuffer = await blob.arrayBuffer();
  const blobValue = new Uint8Array(arrayBuffer);

  return { blobValue, filename };
};