"use server"

import { serverFetchJson, serverFetchString, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { revalidatePath, revalidateTag } from "next/cache";
import { cache } from "react";

export interface InvoiceResult {
  id: number;
  projectCode: string;
  projectName: string;
  stage: string;
  comingPaymentMileStone: string;
  paymentMilestoneDate: string;
  resourceUsage: number;
  unbilledHours: number;
  reminder: string;
}

type InvoiceListError = {
  [field in keyof NewInvoice]?: string;
} & {
message?: string;
};

export type NewInvoice = {
  invoiceNo: string | undefined,
  projectCode: string | undefined,
  issuedDate: Date
  issuedAmount: number,
  receiptDate: Date
  receivedAmount: number
} & {
  _isNew: boolean;
  _error: InvoiceListError
}

export type InvoiceType = {
  data: NewInvoice[]
}

export type PostInvoiceData = {
  invoiceNo: string
  projectId: number
  projectCode: string | undefined,
  issuedAmount: number
  issueDate: string
  receiptDate?: string
  receivedAmount?: number
}
export interface CreateInvoiceInputs {
  id: number;

  // Project Details
  projectCode: string;
  projectName: string;
  stage: string;
  comingPaymentMileStone: string;
  paymentMilestoneDate: string;
  resourceUsage: number;
  unbilledHours: number;

  // Invoice Info
  client: string;
  address: string;
  attention: string;
  invoiceDate: string;
  dueDate: string;
  projectRefNo: string;

  // Invoice related Info
  reminder: string;
  amount: number;
  billHours: number;
}

export interface InvoiceInformation{
  id: number;
  client: string;
  address: string;
  attention: string;
  invoiceDate: string;
  dueDate: string;
  projectRefNo: string;
  
  amount: number;
}

export const fetchProjectInvoiceById = cache(async (id: number) => {
  return serverFetchJson<InvoiceResult[]>(`${BASE_API_URL}/invoices/getProjectDetail/${id}`, {
      next: { tags: ["projectDetailById"] },
    });
})

export const fetchInvoiceInfoById = cache(async (id: number) => {
  return serverFetchJson<InvoiceInformation[]>(`${BASE_API_URL}/invoices/getInvoiceInfo/${id}`, {
      next: { tags: ["invoiceInfoById"] },
    });
})

export const importIssuedInovice = async (data: FormData) => {
  // console.log("----------------",data)
  const importIssuedInovice = await serverFetchJson<any>(
      `${BASE_API_URL}/invoices/import/issued`,
      {
          method: "POST",
          body: data,
          // headers: { "Content-Type": "multipart/form-data" },
      },
  );

  return importIssuedInovice;
};

export const importReceivedInovice = async (data: FormData) => {
  // console.log("----------------",data)
  const importReceivedInovice = await serverFetchJson<any>(
      `${BASE_API_URL}/invoices/import/received`,
      {
          method: "POST",
          body: data,
          // headers: { "Content-Type": "multipart/form-data" },
      },
  );

  return importReceivedInovice;
};

export const importInvoices = async (data: FormData) => {
  const importInvoices = await serverFetchJson<any>(
      `${BASE_API_URL}/invoices/import/v2`,
      {
          method: "POST",
          body: data,
      },
  );

  return importInvoices;
};

export const updateInvoice = async (data: any) => {
  console.log(data)
  const updateInvoice = await serverFetchJson<any>(`${BASE_API_URL}/invoices/update`, {
    method: "Post",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("invoices")
  revalidatePath("/(main)/invoice")
  return updateInvoice;
}

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

  revalidateTag("invoices");
  return invoice;
};

export const createInvoices = async (data: any) => {
  // console.log(data)
  const createInvoices = serverFetchString<any>(`${BASE_API_URL}/invoices/create`, {
    method: "Post",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
});
  revalidateTag("invoices")
  return createInvoices;
}