import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { businessPartner as businessPartnerStub, company as companyStub } from "../lib/_db_deps";
import { salesOrder } from "./salesOrder";
import { salesPaymentTerm } from "./salesPaymentTerm";
import { shipment } from "./shipment";

export const SALES_INVOICE_STATUSES: [string, string, string, string] = [
  "DRAFT",
  "ISSUED",
  "SENT",
  "CANCELLED",
];

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

export function createSalesInvoiceType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSalesInvoiceTypeParams<F>,
) {
  return db
    .type("SalesInvoice", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "salesInvoices",
        })
        .description("Foreign key to Company"),
      customerId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.customerType ?? businessPartnerStub },
          backward: "salesInvoices",
        })
        .description("Foreign key to Customer"),
      salesOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.salesOrderType ?? salesOrder },
          backward: "salesInvoices",
        })
        .description("Foreign key to SalesOrder"),
      paymentTermId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.paymentTermType ?? salesPaymentTerm },
          backward: "salesInvoices",
        })
        .description("Optional payment term"),
      shipmentId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.shipmentType ?? shipment },
          backward: "salesInvoices",
        })
        .description("Optional shipment evidence"),
      status: db.enum(SALES_INVOICE_STATUSES).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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const salesInvoice = createSalesInvoiceType({});
