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

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

export interface ListProfitCentersInput extends PaginationInput<ProfitCenterOrderByField> {
  companyId?: string;
  status?: string;
}

/**
 * Function: listProfitCenters
 *
 * Lists profit centers with optional filter for status.
 */
export async function run(db: ReadonlyDB<DB>, input: ListProfitCentersInput) {
  if (
    input.status &&
    !(["DRAFT", "ACTIVE", "INACTIVE"] as const satisfies ProfitCenterStatus[]).includes(
      input.status as ProfitCenterStatus,
    )
  ) {
    return err(new InvalidStatusFilterError(input.status));
  }

  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("ProfitCenter").selectAll();

  if (input.companyId) {
    query = query.where("companyId", "=", input.companyId);
  }
  if (input.status) {
    query = query.where("status", "=", input.status as ProfitCenterStatus);
  }

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

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