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

const builtins = (params: { companyType?: TailorAnyDBType; customerType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const customerId = db.uuid().description("Foreign key to Customer");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "salesCreditNotes",
        })
      : companyId,
    customerId: params.customerType
      ? customerId.relation({
          type: "n-1",
          toward: { type: params.customerType },
          backward: "salesCreditNotes",
        })
      : customerId,
    salesInvoiceId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: 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"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

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

export const salesCreditNote = createSalesCreditNoteType({});
