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

type OrderByField = "expirationDate" | "manufactureDate" | "lotNumber" | "createdAt";

export interface ListLotsInput extends PaginationInput<OrderByField> {
  itemId?: string;
  siteId?: string;
  status?: LotStatus;
}

export async function run(db: ReadonlyDB<DB>, input: ListLotsInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "expirationDate";
  const orderDirection = input.orderDirection ?? "asc";

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

  if (input.itemId) {
    query = query.where("Lot.itemId", "=", input.itemId);
  }
  if (input.status) {
    query = query.where("Lot.status", "=", input.status);
  }
  if (input.siteId) {
    const locationIds = await db
      .selectFrom("StorageLocation")
      .select("id")
      .where("siteId", "=", input.siteId)
      .execute();

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

    const lotIds = await db
      .selectFrom("LotStockLevel")
      .select("lotId")
      .where(
        "storageLocationId",
        "in",
        locationIds.map((l) => l.id),
      )
      .execute();

    const uniqueLotIds = [...new Set(lotIds.map((l) => l.lotId))];
    if (uniqueLotIds.length === 0) {
      return ok(buildPaginatedResult([], limit));
    }

    query = query.where("Lot.id", "in", uniqueLotIds);
  }

  const lots = await query
    .orderBy(`Lot.${orderBy}`, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

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