import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { unitLifecycle } from "./unit.lifecycle.generated";
import { uomCategory } from "./uomCategory";

const builtins = {
  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: uomCategory },
      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"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createUnitType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateUnitTypeParams<F>,
) {
  return db
    .type("Unit", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const unit = createUnitType({});
