import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { businessPartner as businessPartnerStub, company as companyStub } from "../lib/_db_deps";
import { salesCreditNoteLifecycle } from "./salesCreditNote.lifecycle.generated";
import { salesInvoice } from "./salesInvoice";

export interface CreateSalesCreditNoteTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  customerType?: TailorAnyDBType;
  salesInvoiceType?: TailorAnyDBType;
}

export function createSalesCreditNoteType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSalesCreditNoteTypeParams<F>,
) {
  return db
    .type("SalesCreditNote", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "salesCreditNotes",
        })
        .description("Foreign key to Company"),
      customerId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.customerType ?? businessPartnerStub },
          backward: "salesCreditNotes",
        })
        .description("Foreign key to Customer"),
      salesInvoiceId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.salesInvoiceType ?? salesInvoice },
          backward: "salesCreditNotes",
        })
        .description("Foreign key to SalesInvoice"),
      status: db.enum(salesCreditNoteLifecycle.states).description("Credit-note lifecycle status"),
      creditNoteNumber: db.string({ optional: true }).description("Optional document number"),
      creditDate: db.date().description("Credit-note date"),
      reason: db.string({ optional: true }).description("Correction reason"),
      correctionSnapshot: db
        .string({ optional: true })
        .description("Serialized correction snapshot context"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const salesCreditNote = createSalesCreditNoteType({});
