import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { item as itemStub } from "../lib/_db_deps";
import { valuationPolicy } from "./valuationPolicy";

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

export function createItemValuationType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateItemValuationTypeParams<F>,
) {
  return db
    .type("ItemValuation", {
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: itemStub },
          backward: "itemValuations",
        })
        .description("Foreign key to Item"),
      valuationPolicyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: valuationPolicy },
          backward: "itemValuations",
        })
        .description("Foreign key to ValuationPolicy"),
      totalQuantity: db.float().description("Total quantity in inventory"),
      totalValue: db.float().description("Total inventory value"),
      costPerUnit: db.float().description("Computed cost per unit (totalValue / totalQuantity)"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["itemId", "valuationPolicyId"],
      unique: true,
      name: "item_valuation_item_policy_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const itemValuation = createItemValuationType({});
