import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { site as siteStub } from "../lib/_db_deps";
import { storageLocationLifecycle } from "./storageLocation.lifecycle.generated";

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

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 site"),
      code: db.string({ optional: true }).description("Location code, unique within site"),
      siteId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "storageLocations",
        })
        .description("Foreign key to Site"),
      storageCondition: db
        .string({ optional: true })
        .description("Storage condition: ambient, cold, hazardous"),
      capacity: db.decimal({ optional: true }).description("Optional storage capacity"),
      status: db.enum(storageLocationLifecycle.states).description("Lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const storageLocation = createStorageLocationType({ siteType: siteStub });
