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

export const PLAN_VERSION_TYPES = ["BUDGET", "FORECAST", "SIMULATION"] as const;

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

export function createPlanVersionType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePlanVersionTypeParams<F>,
) {
  return db
    .type("PlanVersion", {
      name: db.string().description("Plan version name"),
      type: db.enum([...PLAN_VERSION_TYPES]).description("Plan version type"),
      baseVersionId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: "self" },
          backward: "derivedVersions",
        })
        .description("Foreign key to base PlanVersion"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "planVersions",
        })
        .description("Foreign key to Company"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const planVersion = createPlanVersionType({});
