import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { purchaseBill } from "./purchaseBill";
import { purchaseOrderLine } from "./purchaseOrderLine";

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

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"),
      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(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const purchaseBillLine = createPurchaseBillLineType({});
