"use server";

import { serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { Contact, Subsidiary, SaveSubsidiaryResponse,  } from ".";
import { revalidateTag } from "next/cache";

export interface SubsidiaryFormInputs {

    // Subsidiary info
    id: number | null;
    name: string;
    code: string;
    address: string | null;
    district: string | null;
    brNo: string | null;
    typeId: number;

    // Customer
    addCustomerIds: number[];
    deleteCustomerIds: number[];

    // Contact
    addContacts: Contact[];
    deleteContactIds: number[];

    // is grid editing
    isGridEditing: boolean | null;
}

export interface SubsidiaryResponse {
    subsidiary: Subsidiary;
    customerIds: number[];
    contacts: Contact[];
}

export const saveSubsidiary = async (data: SubsidiaryFormInputs) => {
    const saveSubsidiary = await serverFetchJson<SaveSubsidiaryResponse>(
        `${BASE_API_URL}/subsidiary/save`,
        {
            method: "POST",
            body: JSON.stringify(data),
            headers: { "Content-Type": "application/json" },
        },
    );

    revalidateTag("subsidiaries");

    return saveSubsidiary;
};

export const fetchSubsidiary = async (id: number) => {
    const subsidiary = await serverFetchJson<SubsidiaryResponse>(
        `${BASE_API_URL}/subsidiary/${id}`,
        {
            method: "GET",
            headers: { "Content-Type": "application/json" },
        },
    );

    return subsidiary
};

export const deleteSubsidiary = async (id: number) => {
    const subsidiary = await serverFetchWithNoContent(
        `${BASE_API_URL}/subsidiary/${id}`,
        {
            method: "DELETE",
            headers: { "Content-Type": "application/json" },
        },
    );

    revalidateTag("subsidiaries");

    return subsidiary
};