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

type OrderByField = "serialNumber" | "createdAt";

export interface ListSerialNumbersInput extends PaginationInput<OrderByField> {
  itemId?: string;
  storageLocationId?: string;
  status?: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListSerialNumbersInput) {
  if (!input.itemId && !input.storageLocationId && !input.status) {
    return err(new NoFilterProvidedError("listSerialNumbers"));
  }

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

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

  if (input.itemId) {
    query = query.where("itemId", "=", input.itemId);
  }
  if (input.storageLocationId) {
    query = query.where("storageLocationId", "=", input.storageLocationId);
  }
  if (input.status) {
    query = query.where(
      "status",
      "=",
      input.status as "AVAILABLE" | "ISSUED" | "RETURNED" | "SCRAPPED",
    );
  }

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

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