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

type BudgetOrderByField = "name" | "createdAt";

export interface ListBudgetsInput extends PaginationInput<BudgetOrderByField> {
  companyId?: string;
  status?: string;
  fiscalYearId?: string;
  costObjectType?: string;
  costObjectId?: string;
  planVersionId?: string;
}

/**
 * Function: listBudgets
 *
 * Lists budgets with optional filters for status, fiscal year, cost object type,
 * and cost object ID.
 */
export async function run(db: ReadonlyDB<DB>, input: ListBudgetsInput) {
  if (
    input.status &&
    !(
      ["DRAFT", "SUBMITTED", "APPROVED", "ACTIVE", "CLOSED"] as const satisfies BudgetStatus[]
    ).includes(input.status as BudgetStatus)
  ) {
    return err(new InvalidStatusFilterError(input.status));
  }

  if (
    input.costObjectType &&
    !(["CostCenter", "ProfitCenter", "InternalOrder"] as const).includes(
      input.costObjectType as "CostCenter" | "ProfitCenter" | "InternalOrder",
    )
  ) {
    return err(new InvalidCostObjectTypeFilterError(input.costObjectType));
  }

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

  if (input.companyId) {
    query = query.where("companyId", "=", input.companyId);
  }
  if (input.status) {
    query = query.where("status", "=", input.status as BudgetStatus);
  }
  if (input.fiscalYearId) {
    query = query.where("fiscalYearId", "=", input.fiscalYearId);
  }
  if (input.costObjectType) {
    query = query.where("costObjectType", "=", input.costObjectType);
  }
  if (input.costObjectId) {
    query = query.where("costObjectId", "=", input.costObjectId);
  }
  if (input.planVersionId) {
    query = query.where("planVersionId", "=", input.planVersionId);
  }

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

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