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

const builtins = (params: { siteType?: TailorAnyDBType }) => {
  const siteId = db.uuid().description("Foreign key to Site");
  return {
    name: db.string().description("Location display name, unique within site"),
    code: db.string({ optional: true }).description("Location code, unique within site"),
    siteId: params.siteType
      ? siteId.relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "storageLocations",
        })
      : siteId,
    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"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

export function createStorageLocationType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateStorageLocationTypeParams<F>,
) {
  return db
    .type("StorageLocation", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const storageLocation = createStorageLocationType({});
