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

type CostCenterOrderByField = "name" | "code" | "createdAt";

export interface ListCostCentersInput extends PaginationInput<CostCenterOrderByField> {
  companyId?: string;
  category?: string;
  hierarchyNodeId?: string;
}

/**
 * Function: listCostCenters
 *
 * Lists cost centers with optional filter for category.
 */
export async function run(db: ReadonlyDB<DB>, input: ListCostCentersInput) {
  if (
    input.category &&
    !(["overhead", "production", "administration", "sales", "research"] as const).includes(
      input.category as "overhead" | "production" | "administration" | "sales" | "research",
    )
  ) {
    return err(new InvalidCategoryFilterError(input.category));
  }

  if (input.hierarchyNodeId) {
    const hierarchyNode = await db
      .selectFrom("CostCenterHierarchyNode")
      .select("id")
      .where("id", "=", input.hierarchyNodeId)
      .executeTakeFirst();

    if (!hierarchyNode) {
      return err(new HierarchyNodeNotFoundError(input.hierarchyNodeId));
    }
  }

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

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

  if (input.companyId) {
    query = query.where("companyId", "=", input.companyId);
  }
  if (input.category) {
    query = query.where("category", "=", input.category);
  }
  if (input.hierarchyNodeId) {
    query = query.where("hierarchyNodeId", "=", input.hierarchyNodeId);
  }

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

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