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

export const LOT_STATUSES = ["ACTIVE", "FULLY_CONSUMED"] as const;

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

export function createLotType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateLotTypeParams<F>,
) {
  return db
    .type("Lot", {
      lotNumber: db.string().description("Lot/batch number, unique per item"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: itemStub },
          backward: "lots",
        })
        .description("Foreign key to Item"),
      manufactureDate: db.datetime({ optional: true }).description("Date of manufacture"),
      expirationDate: db
        .datetime({ optional: true })
        .description("Expiration date for shelf-life tracking"),
      supplierLotReference: db
        .string({ optional: true })
        .description("Supplier's lot reference for traceability"),
      status: db
        .enum([...LOT_STATUSES] as [string, ...string[]])
        .description("Consumption status: ACTIVE or FULLY_CONSUMED"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["lotNumber", "itemId"],
      unique: true,
      name: "lot_number_item_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const lot = createLotType({});
