import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { businessPartner as businessPartnerStub, company as companyStub } from "../lib/_db_deps";
import { salesInvoice } from "./salesInvoice";

export const SALES_CREDIT_NOTE_STATUSES: [string, string] = ["DRAFT", "ISSUED"];

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

export const salesCreditNote = createSalesCreditNoteType({});
