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 = "plannedDate" | "createdAt";

export interface ListInventoryCountsInput extends PaginationInput<OrderByField> {
  status?: string;
  countType?: string;
  warehouseId?: string;
  dateFrom?: Date;
  dateTo?: Date;
}

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

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

  if (input.status) {
    query = query.where(
      "status",
      "=",
      input.status as "PLANNED" | "IN_PROGRESS" | "COMPLETED" | "CANCELLED",
    );
  }
  if (input.countType) {
    query = query.where("countType", "=", input.countType as "FULL" | "CYCLE");
  }
  if (input.warehouseId) {
    query = query.where("warehouseId", "=", input.warehouseId);
  }
  if (input.dateFrom) {
    query = query.where("plannedDate", ">=", input.dateFrom);
  }
  if (input.dateTo) {
    query = query.where("plannedDate", "<=", input.dateTo);
  }

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

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