import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { unit as unitStub } from "../lib/_db_deps";
import { purchaseBill } from "./purchaseBill";
import { purchaseOrderLine } from "./purchaseOrderLine";

export interface CreatePurchaseBillLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  unitType: TailorAnyDBType;
}

export function createPurchaseBillLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchaseBillLineTypeParams<F>,
) {
  return db
    .type("PurchaseBillLine", {
      purchaseBillId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseBill },
          backward: "lines",
        })
        .description("Foreign key to PurchaseBill"),
      purchaseOrderLineId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: purchaseOrderLine },
          backward: "purchaseBillLines",
        })
        .description("Foreign key to PurchaseOrderLine (nullable for bills without a PO)"),
      quantity: db.decimal().description("Billed quantity"),
      billedUnitPrice: db.decimal({ optional: true }).description("Billed unit price"),
      unitId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "purchaseBillLines",
        })
        .description("Unit of measure"),
      taxCode: db.string({ optional: true }).description("Tax code"),
      taxableAmount: db.decimal({ optional: true }).description("Taxable amount"),
      taxAmount: db.decimal({ optional: true }).description("Tax amount"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchaseBillLine = createPurchaseBillLineType({
  unitType: unitStub,
});
