import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { accountingPeriod as accountingPeriodStub, company as companyStub } from "../lib/_db_deps";
import { allocationCycleLifecycle } from "./allocationCycle.lifecycle.generated";

export const ALLOCATION_TYPES = ["ASSESSMENT", "DISTRIBUTION"] as const;

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

export function createAllocationCycleType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateAllocationCycleTypeParams<F>,
) {
  return db
    .type("AllocationCycle", {
      name: db.string().description("Allocation cycle name"),
      allocationType: db.enum(ALLOCATION_TYPES).description("Allocation type"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "allocationCycles",
        })
        .description("Foreign key to Company"),
      accountingPeriodId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.accountingPeriodType ?? accountingPeriodStub },
          backward: "allocationCycles",
        })
        .description("Foreign key to AccountingPeriod"),
      status: db
        .enum(allocationCycleLifecycle.states)
        .description("Allocation cycle lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const allocationCycle = createAllocationCycleType({});
