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

export interface ListStorageLocationsInput extends PaginationInput<OrderByField> {
  warehouseId?: string;
  status?: string;
  parentId?: string | null;
}

export async function run(db: ReadonlyDB<DB>, input: ListStorageLocationsInput) {
  if (!input.warehouseId && !input.status && input.parentId === undefined) {
    return err(new NoFilterProvidedError("listStorageLocations"));
  }

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

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

  if (input.warehouseId) {
    query = query.where("warehouseId", "=", input.warehouseId);
  }
  if (input.status) {
    query = query.where("status", "=", input.status as "ACTIVE" | "INACTIVE");
  }
  if (input.parentId !== undefined) {
    if (input.parentId === null) {
      query = query.where("parentId", "is", null);
    } else {
      query = query.where("parentId", "=", input.parentId);
    }
  }

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

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