import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { salesInvoiceLifecycle } from "./salesInvoice.lifecycle.generated";
import { salesOrder } from "./salesOrder";
import { salesPaymentTerm } from "./salesPaymentTerm";
import { shipment } from "./shipment";

const builtins = (params: { companyType?: TailorAnyDBType; customerType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const customerId = db.uuid().description("Foreign key to Customer");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "salesInvoices",
        })
      : companyId,
    customerId: params.customerType
      ? customerId.relation({
          type: "n-1",
          toward: { type: params.customerType },
          backward: "salesInvoices",
        })
      : customerId,
    salesOrderId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: salesOrder },
        backward: "salesInvoices",
      })
      .description("Foreign key to SalesOrder"),
    paymentTermId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: salesPaymentTerm },
        backward: "salesInvoices",
      })
      .description("Optional payment term"),
    shipmentId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: shipment },
        backward: "salesInvoices",
      })
      .description("Optional shipment evidence"),
    status: db.enum(salesInvoiceLifecycle.states).description("Sales-invoice lifecycle status"),
    invoiceNumber: db.string({ optional: true }).description("Optional invoice number"),
    invoiceDate: db.date().description("Invoice date"),
    billingPolicy: db.string({ optional: true }).description("Invoice billing policy"),
    paymentTermSnapshot: db
      .string({ optional: true })
      .description("Serialized payment-term snapshot"),
    dueSchedule: db.string({ optional: true }).description("Serialized due schedule"),
    taxIdentitySnapshot: db
      .string({ optional: true })
      .description("Serialized tax identity snapshot"),
    deliveryMetadata: db.string({ optional: true }).description("Serialized delivery metadata"),
    arHandoffAccepted: db.bool().description("Whether AR handoff already accepted the invoice"),
    notes: db.string({ optional: true }).description("Optional notes"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

export interface CreateSalesInvoiceTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
  companyType?: TailorAnyDBType;
  customerType?: TailorAnyDBType;
}

export function createSalesInvoiceType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSalesInvoiceTypeParams<F>,
) {
  return db
    .type("SalesInvoice", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const salesInvoice = createSalesInvoiceType({});
