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

export interface CreateSalesCreditNoteLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  salesCreditNoteType?: TailorAnyDBType;
  salesInvoiceLineType?: TailorAnyDBType;
}

export function createSalesCreditNoteLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSalesCreditNoteLineTypeParams<F>,
) {
  return db
    .type("SalesCreditNoteLine", {
      salesCreditNoteId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.salesCreditNoteType ?? salesCreditNote },
          backward: "lines",
        })
        .description("Foreign key to SalesCreditNote"),
      salesInvoiceLineId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.salesInvoiceLineType ?? 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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const salesCreditNoteLine = createSalesCreditNoteLineType({});
