import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { salesInvoice } from "./salesInvoice";
import { salesOrderLine } from "./salesOrderLine";
import { shipmentLine } from "./shipmentLine";

const builtins = {
  salesInvoiceId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: salesInvoice },
      backward: "lines",
    })
    .description("Foreign key to SalesInvoice"),
  salesOrderLineId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: salesOrderLine },
      backward: "invoiceLines",
    })
    .description("Foreign key to SalesOrderLine"),
  shipmentLineId: db
    .uuid({ optional: true })
    .relation({
      type: "n-1",
      toward: { type: 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"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

export interface CreateSalesInvoiceLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
}

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

export const salesInvoiceLine = createSalesInvoiceLineType({});
