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

export const COST_ELEMENT_STATUSES = ["DRAFT", "ACTIVE", "INACTIVE"] as const;

export const COST_ELEMENT_TYPES = ["PRIMARY", "SECONDARY"] as const;

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

export function createCostElementType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateCostElementTypeParams<F>,
) {
  return db
    .type("CostElement", {
      code: db.string().description("Cost element code"),
      name: db.string().description("Cost element name"),
      type: db.enum([...COST_ELEMENT_TYPES]).description("Cost element type"),
      category: db.string().description("Cost element category"),
      description: db.string({ optional: true }).description("Cost element description"),
      glAccountId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.accountType ?? accountStub },
          backward: "costElements",
        })
        .description("Foreign key to Account"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "costElements",
        })
        .description("Foreign key to Company"),
      validFrom: db.date({ optional: true }).description("Valid from date"),
      validTo: db.date({ optional: true }).description("Valid to date"),
      status: db.enum([...COST_ELEMENT_STATUSES]).description("Cost element lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const costElement = createCostElementType({});
