import { serverFetchJson } 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 CustomerTable {
  id: number;
  code: string;
  name: string;
  brNo: string | null;
  address: string | null;
  district: string | null;
  customerType: string;

  contacts: Contact[];
}

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

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

export interface Subsidiary {
  id: number;
  code: string;
  name: string;
  brNo: string | null;
  address: string | null;
  district: string | null;
  subsidiaryType: SubsidiaryType;

  contacts: Contact[];
}

export interface SaveSubsidiaryResponse {
  subsidiary: Subsidiary;
  message: string;
}

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

export const preloadAllSubsidiaries = () => {
  fetchAllSubsidiaries();
};

export const fetchAllCustomers = cache(async () => {
  return serverFetchJson<Customer[]>(`${BASE_API_URL}/customer`);
});

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

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