import type { DB } from "../generated/kysely-tailordb";
import { NoFilterProvidedError } from "../lib/errors.generated";
import {
  ok,
  err,
  type ReadonlyDB,
  type PaginationInput,
  buildPaginatedResult,
  DEFAULT_PAGE_SIZE,
} from "@tailor-platform/erp-kit/module";

type OrderByField = "createdAt";

export interface ListStockLevelsInput extends PaginationInput<OrderByField> {
  itemId?: string;
  storageLocationId?: string;
  warehouseId?: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListStockLevelsInput) {
  if (!input.itemId && !input.storageLocationId && !input.warehouseId) {
    return err(new NoFilterProvidedError("listStockLevels"));
  }

  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "createdAt";
  const orderDirection = input.orderDirection ?? "asc";

  if (input.warehouseId) {
    const locationIds = await db
      .selectFrom("StorageLocation")
      .select("id")
      .where("warehouseId", "=", input.warehouseId)
      .execute();

    if (locationIds.length === 0) {
      return ok(buildPaginatedResult([], limit));
    }

    let query = db
      .selectFrom("StockLevel")
      .selectAll()
      .where(
        "storageLocationId",
        "in",
        locationIds.map((l) => l.id),
      );

    if (input.itemId) {
      query = query.where("itemId", "=", input.itemId);
    }

    const stockLevels = await query
      .orderBy(orderBy, orderDirection)
      .limit(limit + 1)
      .offset(offset)
      .execute();

    return ok(buildPaginatedResult(stockLevels, limit));
  }

  let query = db.selectFrom("StockLevel").selectAll();

  if (input.itemId) {
    query = query.where("itemId", "=", input.itemId);
  }
  if (input.storageLocationId) {
    query = query.where("storageLocationId", "=", input.storageLocationId);
  }

  const stockLevels = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  return ok(buildPaginatedResult(stockLevels, limit));
}
