import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";

export interface GetStorageLocationInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetStorageLocationInput) {
  const storageLocation = await db
    .selectFrom("StorageLocation")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!storageLocation) {
    return ok({ storageLocation: null, stockLevels: [] });
  }

  const stockLevels = await db
    .selectFrom("StockLevel")
    .selectAll()
    .where("storageLocationId", "=", storageLocation.id)
    .execute();

  return ok({ storageLocation, stockLevels });
}
