import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";

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

const builtins = (params: { itemType?: TailorAnyDBType }) => {
  const itemId = db.uuid().description("Foreign key to Item");
  return {
    lotNumber: db.string().description("Lot/batch number, unique per item"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "lots",
        })
      : itemId,
    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).description("Consumption status: ACTIVE or FULLY_CONSUMED"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

export function createLotType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateLotTypeParams<F>,
) {
  return db
    .type("Lot", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["lotNumber", "itemId"],
      unique: true,
      name: "lot_number_item_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const lot = createLotType({});
