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

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

export interface ListCostElementsInput extends PaginationInput<CostElementOrderByField> {
  companyId?: string;
  type?: string;
  category?: string;
  status?: string;
}

/**
 * Function: listCostElements
 *
 * Lists cost elements with optional filters for type, category, and status.
 */
export async function run(db: ReadonlyDB<DB>, input: ListCostElementsInput) {
  if (
    input.type &&
    !(["PRIMARY", "SECONDARY"] as const satisfies CostElementType[]).includes(
      input.type as CostElementType,
    )
  ) {
    return err(new InvalidTypeFilterError(input.type));
  }

  if (
    input.status &&
    !(["DRAFT", "ACTIVE", "INACTIVE"] as const satisfies CostElementStatus[]).includes(
      input.status as CostElementStatus,
    )
  ) {
    return err(new InvalidStatusFilterError(input.status));
  }

  if (
    input.category &&
    !(
      [
        "overhead",
        "material",
        "labor",
        "depreciation",
        "assessment",
        "distribution",
        "internal_activity_allocation",
        "settlement",
      ] as const
    ).includes(
      input.category as
        | "overhead"
        | "material"
        | "labor"
        | "depreciation"
        | "assessment"
        | "distribution"
        | "internal_activity_allocation"
        | "settlement",
    )
  ) {
    return err(new InvalidCategoryFilterError(input.category));
  }

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

  if (input.companyId) {
    query = query.where("companyId", "=", input.companyId);
  }
  if (input.type) {
    query = query.where("type", "=", input.type as CostElementType);
  }
  if (input.category) {
    query = query.where("category", "=", input.category);
  }
  if (input.status) {
    query = query.where("status", "=", input.status as CostElementStatus);
  }

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

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