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

const builtins = {
  salesCreditNoteId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: salesCreditNote },
      backward: "lines",
    })
    .description("Foreign key to SalesCreditNote"),
  salesInvoiceLineId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: salesInvoiceLine },
      backward: "creditNoteLines",
    })
    .description("Foreign key to SalesInvoiceLine"),
  quantity: db.float({ optional: true }).description("Credited quantity"),
  amount: db.float({ optional: true }).description("Credited amount"),
  reason: db.string({ optional: true }).description("Line-level correction reason"),
  taxAmount: db.float({ optional: true }).description("Credited tax amount"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const salesCreditNoteLine = createSalesCreditNoteLineType({});
