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

export const INVENTORY_EXECUTION_TYPES = [
  "GOODS_RECEIPT",
  "GOODS_ISSUE",
  "STOCK_ADJUSTMENT",
] as const;

export const INVENTORY_EXECUTION_SOURCE_DOCUMENT_TYPES = [
  "PURCHASE_ORDER",
  "SALES_ORDER",
  "TRANSFER_ORDER",
  "MANUFACTURING_ORDER",
  "STOCK_ADJUSTMENT",
] as const;

const builtins = {
  executionType: db
    .enum(INVENTORY_EXECUTION_TYPES)
    .description("Inventory execution type such as GOODS_RECEIPT or GOODS_ISSUE"),
  status: db
    .enum(inventoryExecutionLifecycle.states)
    .description("Posting status. DRAFT does not affect stock; POSTED does."),
  effectiveDate: db
    .date()
    .description("Business effective date used for inventory reporting and period controls"),
  postedAt: db
    .datetime({ optional: true })
    .description("System timestamp when stock effects were posted"),
  sourceDocumentType: db
    .enum(INVENTORY_EXECUTION_SOURCE_DOCUMENT_TYPES, { optional: true })
    .description("Optional source document type such as PURCHASE_ORDER"),
  sourceDocumentId: db
    .uuid({ optional: true })
    .description("Optional source document ID. Generic reference, not a typed foreign key."),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createInventoryExecutionType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateInventoryExecutionTypeParams<F>,
) {
  return db
    .type("InventoryExecution", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes(
      {
        fields: ["executionType", "createdAt"],
        unique: false,
        name: "inventory_execution_type_created_idx",
      },
      {
        fields: ["executionType", "sourceDocumentType", "createdAt"],
        unique: false,
        name: "inventory_execution_type_source_created_idx",
      },
      {
        fields: ["sourceDocumentType", "sourceDocumentId"],
        unique: false,
        name: "inventory_execution_source_document_idx",
      },
    )
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const inventoryExecution = createInventoryExecutionType({});
