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

export const BASE_STORAGE_LOCATION_STATUSES = ["ACTIVE", "INACTIVE"] as const;
export const LOCATION_TYPES = ["zone", "bin"] as const;

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

export function createStorageLocationType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateStorageLocationTypeParams<F>,
) {
  return db
    .type("StorageLocation", {
      name: db.string().description("Location display name, unique within warehouse"),
      code: db.string({ optional: true }).description("Location code, unique within warehouse"),
      warehouseId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: warehouse },
          backward: "storageLocations",
        })
        .description("Foreign key to Warehouse"),
      parentId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: "self" },
          backward: "children",
        })
        .description("Parent storage location (null for zones, zone id for bins)"),
      locationType: db
        .enum([...LOCATION_TYPES] as [string, ...string[]])
        .description("Location type: zone or bin"),
      storageCondition: db
        .string({ optional: true })
        .description("Storage condition: ambient, cold, hazardous"),
      capacity: db.float({ optional: true }).description("Optional storage capacity"),
      status: db
        .enum([...BASE_STORAGE_LOCATION_STATUSES] as [string, ...string[]])
        .description("Lifecycle status: ACTIVE, INACTIVE"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const storageLocation = createStorageLocationType({});
