import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
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"),
      isActive: db.bool().description("Whether the unit is active"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

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