import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { salesInvoice } from "./salesInvoice";
import { salesOrderLine } from "./salesOrderLine";
import { shipmentLine } from "./shipmentLine";

export interface CreateSalesInvoiceLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  salesInvoiceType?: TailorAnyDBType;
  salesOrderLineType?: TailorAnyDBType;
  shipmentLineType?: TailorAnyDBType;
}

export function createSalesInvoiceLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSalesInvoiceLineTypeParams<F>,
) {
  return db
    .type("SalesInvoiceLine", {
      salesInvoiceId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.salesInvoiceType ?? salesInvoice },
          backward: "lines",
        })
        .description("Foreign key to SalesInvoice"),
      salesOrderLineId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.salesOrderLineType ?? salesOrderLine },
          backward: "invoiceLines",
        })
        .description("Foreign key to SalesOrderLine"),
      shipmentLineId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.shipmentLineType ?? shipmentLine },
          backward: "invoiceLines",
        })
        .description("Optional shipment evidence line"),
      quantity: db.float().description("Billed quantity"),
      unitPrice: db.float().description("Billed unit price"),
      taxCode: db.string({ optional: true }).description("Optional tax code"),
      taxableAmount: db.float({ optional: true }).description("Taxable amount"),
      taxAmount: db.float({ optional: true }).description("Tax amount"),
      billingPolicy: db.string({ optional: true }).description("Line billing policy"),
      orderPriceSnapshot: db
        .string({ optional: true })
        .description("Serialized order price snapshot"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const salesInvoiceLine = createSalesInvoiceLineType({});
