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

type OrderByField = "expirationDate" | "createdAt";

export interface ListExpiringLotsInput extends PaginationInput<OrderByField> {
  daysUntilExpiry: number;
  itemId?: string;
  warehouseId?: string;
}

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

  const thresholdDate = new Date();
  thresholdDate.setDate(thresholdDate.getDate() + input.daysUntilExpiry);

  let query = db
    .selectFrom("Lot")
    .selectAll("Lot")
    .where("Lot.expirationDate", "is not", null)
    .where("Lot.expirationDate", "<=", thresholdDate)
    .where("Lot.status", "=", "ACTIVE");

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

  if (input.warehouseId) {
    const locationIds = await db
      .selectFrom("StorageLocation")
      .select("id")
      .where("warehouseId", "=", input.warehouseId)
      .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));
}
