import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";

export const MOVEMENT_TYPES = [
  "GOODS_RECEIPT",
  "GOODS_ISSUE",
  "INTERNAL_TRANSFER",
  "BLOCK",
  "UNBLOCK",
] as const;

export const BASE_STOCK_MOVEMENT_STATUSES = ["DRAFT", "CONFIRMED", "DONE", "CANCELLED"] as const;

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

export function createStockMovementType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateStockMovementTypeParams<F>,
) {
  return db
    .type("StockMovement", {
      movementType: db
        .enum([...MOVEMENT_TYPES] as [string, ...string[]])
        .description(
          "Movement type: GOODS_RECEIPT, GOODS_ISSUE, INTERNAL_TRANSFER, BLOCK, UNBLOCK",
        ),
      reasonCode: db
        .string({ optional: true })
        .description("Reason code, required for BLOCK and UNBLOCK"),
      status: db
        .enum([...BASE_STOCK_MOVEMENT_STATUSES] as [string, ...string[]])
        .description("Lifecycle status: DRAFT, CONFIRMED, DONE, CANCELLED"),
      executedAt: db
        .datetime({ optional: true })
        .description("Timestamp when the movement was executed"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const stockMovement = createStockMovementType({});
