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

export const LINE_ADJUSTMENT_DIRECTIONS = ["INCREASE", "DECREASE"] as const;

export const STOCK_CATEGORIES = ["AVAILABLE", "BLOCKED"] as const;

const builtins = (params: { itemType?: TailorAnyDBType }) => {
  const itemId = db.uuid().description("Foreign key to Item");
  return {
    stockAdjustmentId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: stockAdjustment },
        backward: "stockAdjustmentLines",
      })
      .description("Foreign key to StockAdjustment"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "stockAdjustmentLines",
        })
      : itemId,
    storageLocationId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: storageLocation },
        backward: "stockAdjustmentLines",
      })
      .description("Storage location where the adjustment occurs"),
    quantity: db.decimal().description("Quantity (always positive)"),
    adjustmentDirection: db
      .enum([...LINE_ADJUSTMENT_DIRECTIONS] as [string, ...string[]], { optional: true })
      .description("Direction of stock adjustment (required for CORRECTION): INCREASE or DECREASE"),
    fromStockCategory: db
      .enum([...STOCK_CATEGORIES] as [string, ...string[]], { optional: true })
      .description(
        "Source stock category (only used for SCRAP): AVAILABLE (default) or BLOCKED for scrapping blocked stock",
      ),
    unitCost: db.decimal({ optional: true }).description("Cost per unit (optional)"),
    lotId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: lot },
        backward: "stockAdjustmentLines",
      })
      .description("Optional foreign key to Lot for lot-tracked items"),
    serialNumberId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: serialNumber },
        backward: "stockAdjustmentLines",
      })
      .description("Optional foreign key to SerialNumber for serial-tracked items"),
  };
};

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

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

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

export const stockAdjustmentLine = createStockAdjustmentLineType({});
