"use server";

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


export interface CustomerFormInputs {

    // Customer details
    id: number | null;
    name: string;
    code: string;
    address: string | null;
    district: string | null;
    brNo: string | null;
    typeId: number;

    // Subsidiary
    addSubsidiaryIds: number[];
    deleteSubsidiaryIds: number[];

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

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

export interface CustomerResponse {
    customer: Customer;
    subsidiaryIds: number[];
    contacts: Contact[];
}

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

    revalidateTag("customers");

    return saveCustomer;
};

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

    return customer
};

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