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

export const COUNT_TYPES = ["FULL", "CYCLE"] as const;
export const BASE_INVENTORY_COUNT_STATUSES = [
  "PLANNED",
  "IN_PROGRESS",
  "COMPLETED",
  "CANCELLED",
] as const;

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

export function createInventoryCountType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateInventoryCountTypeParams<F>,
) {
  return db
    .type("InventoryCount", {
      countType: db
        .enum([...COUNT_TYPES] as [string, ...string[]])
        .description("Count type: FULL (entire warehouse) or CYCLE (specific locations)"),
      warehouseId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: warehouse },
          backward: "inventoryCounts",
        })
        .description("Optional foreign key to Warehouse for full counts"),
      storageLocationId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: storageLocation },
          backward: "inventoryCounts",
        })
        .description("Optional foreign key to StorageLocation for cycle counts"),
      plannedDate: db.datetime().description("Planned date for the count session"),
      status: db
        .enum([...BASE_INVENTORY_COUNT_STATUSES] as [string, ...string[]])
        .description("Lifecycle status: PLANNED, IN_PROGRESS, COMPLETED, CANCELLED"),
      isFrozen: db.bool().description("Whether stock movements are frozen for counted locations"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const inventoryCount = createInventoryCountType({});
