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

export interface Customer {
  id: number;
  code: string;
  name: string;
  brNo: string | null;
  address: string | null;
  district: string | null;
  customerType: CustomerType;
  contacts: Contact[];
}

export interface SaveCustomerResponse {
  customer: Customer;
  message: string;
}

export interface CustomerType {
  id: number;
  name: string;
}

export interface SubsidiaryType {
  id: number;
  name: string;
}

export interface Subsidiary {
  id: number;
  code: string;
  name: string;
  description: string | null;
  brNo: string | null;
  contactName: string | null;
  phone: string | null;
  address: string | null;
  district: string | null;
  email: string | null;
  subsidiaryType: SubsidiaryType;
  subsidiaryContacts: Contact[];
}

export interface SubsidiaryTable {
  id: number;
  code: string;
  name: string;
  description: string | null;
  brNo: string | null;
  contactName: string | null;
  phone: string | null;
  address: string | null;
  district: string | null;
  email: string | null;
  subsidiaryType: string;
  subsidiaryContacts: Contact[];
}

export interface Contact {
  id: number;
  name: string;
  phone: string;
  email: string;
  isNew: boolean;
}

export const preloadAllCustomers = () => {
  fetchAllCustomers();
};

export const fetchAllCustomers = cache(async () => {
  return serverFetchJson<Customer[]>(`${BASE_API_URL}/customer`, {
    next: { tags: ["customers"]}
  });
});

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

export const fetchCustomerTypes = cache(async () => {
  return serverFetchJson<CustomerType[]>(`${BASE_API_URL}/customer/types`, {
    next: { tags: ["customerTypes"] },
  });
});

export const getMaxCustomerCode = cache(async () => {
  return serverFetchString<string>(`${BASE_API_URL}/customer/getMaxCode`, {
    next: { tags: ["customerMaxCode"] },
  });
});
