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

export const ADJUSTMENT_TYPES = ["CORRECTION", "SCRAP", "BLOCK", "UNBLOCK"] as const;

const builtins = {
  adjustmentType: db
    .enum([...ADJUSTMENT_TYPES] as [string, ...string[]])
    .description("Adjustment type: CORRECTION, SCRAP, BLOCK, UNBLOCK"),
  status: db
    .enum(stockAdjustmentLifecycle.states)
    .description("Lifecycle status: DRAFT, SUBMITTED, REJECTED, CONFIRMED, CANCELLED"),
  reasonCode: db.string().description("Reason code explaining why the adjustment is being made"),
  adjustmentDate: db
    .date()
    .description("Business date when the stock adjustment should affect inventory"),
  rejectionReason: db
    .string({ optional: true })
    .description("Optional reason captured when the adjustment is rejected"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const stockAdjustment = createStockAdjustmentType({});
