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

type OrderByField = "createdAt" | "expectedDate";

export interface ListInventorySupplyPlansInput extends PaginationInput<OrderByField> {
  itemId?: string;
  siteId?: string;
  sourceType?: InventorySupplyPlanSourceType;
  sourceId?: string;
  sourceLineId?: string;
  expectedFrom?: Date;
  expectedTo?: Date;
}

export async function run(db: ReadonlyDB<DB>, input: ListInventorySupplyPlansInput) {
  if (
    !input.itemId &&
    !input.siteId &&
    !input.sourceType &&
    !input.sourceId &&
    !input.sourceLineId &&
    !input.expectedFrom &&
    !input.expectedTo
  ) {
    return err(new NoFilterProvidedError("listInventorySupplyPlans"));
  }

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

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

  query = query.where("status", "=", "OPEN");

  if (input.itemId) {
    query = query.where("itemId", "=", input.itemId);
  }
  if (input.siteId) {
    query = query.where("siteId", "=", input.siteId);
  }
  if (input.sourceType) {
    query = query.where("sourceType", "=", input.sourceType);
  }
  if (input.sourceId) {
    query = query.where("sourceId", "=", input.sourceId);
  }
  if (input.sourceLineId) {
    query = query.where("sourceLineId", "=", input.sourceLineId);
  }
  if (input.expectedFrom) {
    query = query.where("expectedDate", ">=", input.expectedFrom);
  }
  if (input.expectedTo) {
    query = query.where("expectedDate", "<=", input.expectedTo);
  }

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

  const items = supplyPlans.map((row) => ({
    ...row,
    openQuantity: getOpenInventorySupplyPlanQuantity(row).toString(),
  }));

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