import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { unitLifecycle } from "./unit.lifecycle.generated";
import { uomCategory } from "./uomCategory";

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

export function createUnitType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateUnitTypeParams<F>,
) {
  return db
    .type("Unit", {
      name: db.string().description("Unit display name (e.g., Kilogram)"),
      symbol: db.string().unique().description("Short symbol (e.g., kg)"),
      categoryId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.uomCategoryType },
          backward: "units",
        })
        .description("Foreign key to UoMCategory"),
      conversionFactor: db
        .float()
        .description("Multiplier relative to reference unit (reference unit = 1.0)"),
      roundingPrecision: db.int().description("Decimal places for rounding"),
      status: db.enum(unitLifecycle.states).description("Lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const unit = createUnitType({ uomCategoryType: uomCategory });
