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

export interface CreateCommitmentTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  costElementType?: TailorAnyDBType;
  companyType?: TailorAnyDBType;
  accountingPeriodType?: TailorAnyDBType;
}

export function createCommitmentType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateCommitmentTypeParams<F>,
) {
  return db
    .type("Commitment", {
      costElementId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.costElementType ?? costElement },
          backward: "commitments",
        })
        .description("Foreign key to CostElement"),
      costObjectType: db.string().description("Polymorphic type of the cost object"),
      costObjectId: db.uuid().description("Polymorphic ID of the cost object"),
      accountingPeriodId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.accountingPeriodType ?? accountingPeriodStub },
          backward: "commitments",
        })
        .description("Foreign key to AccountingPeriod"),
      amount: db.float().description("Committed amount"),
      consumedAmount: db.float().description("Amount consumed from the commitment"),
      purchaseOrderId: db.uuid().description("Reference to external purchase order"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "commitments",
        })
        .description("Foreign key to Company"),
      status: db.string().description("Current status of the commitment"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const commitment = createCommitmentType({});
