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

export const ALLOCATION_CYCLE_STATUSES = [
  "DRAFT",
  "VALIDATED",
  "EXECUTED",
  "POSTED",
  "REVERSED",
] as const;

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([...ALLOCATION_CYCLE_STATUSES])
        .description("Allocation cycle lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const allocationCycle = createAllocationCycleType({});
