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

export interface ListInventoryAdjustmentsInput extends PaginationInput<OrderByField> {
  adjustmentType?: string;
  status?: string;
  storageLocationId?: string;
  itemId?: string;
  dateFrom?: Date;
  dateTo?: Date;
}

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

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

  if (input.adjustmentType) {
    query = query.where("adjustmentType", "=", input.adjustmentType as "CORRECTION" | "SCRAP");
  }
  if (input.status) {
    query = query.where(
      "status",
      "=",
      input.status as "DRAFT" | "PENDING_APPROVAL" | "APPROVED" | "REJECTED" | "CONFIRMED",
    );
  }
  if (input.storageLocationId) {
    query = query.where("storageLocationId", "=", input.storageLocationId);
  }
  if (input.itemId) {
    query = query.where("itemId", "=", input.itemId);
  }
  if (input.dateFrom) {
    query = query.where("createdAt", ">=", input.dateFrom);
  }
  if (input.dateTo) {
    query = query.where("createdAt", "<=", input.dateTo);
  }

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

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