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

type AllocationCycleOrderByField = "name" | "createdAt";

export interface ListAllocationCyclesInput extends PaginationInput<AllocationCycleOrderByField> {
  companyId?: string;
  type?: string;
  status?: string;
  accountingPeriodId?: string;
}

/**
 * Function: listAllocationCycles
 *
 * Lists allocation cycles with optional filters for allocation type, status,
 * and accounting period.
 */
export async function run(db: ReadonlyDB<DB>, input: ListAllocationCyclesInput) {
  if (
    input.type &&
    !(["ASSESSMENT", "DISTRIBUTION"] as const satisfies AllocationCycleAllocationType[]).includes(
      input.type as AllocationCycleAllocationType,
    )
  ) {
    return err(new InvalidTypeFilterError(input.type));
  }

  if (
    input.status &&
    !(
      [
        "DRAFT",
        "VALIDATED",
        "EXECUTED",
        "POSTED",
        "REVERSED",
      ] as const satisfies AllocationCycleStatus[]
    ).includes(input.status as AllocationCycleStatus)
  ) {
    return err(new InvalidStatusFilterError(input.status));
  }

  if (input.accountingPeriodId) {
    const accountingPeriod = await db
      .selectFrom("AccountingPeriod")
      .select("id")
      .where("id", "=", input.accountingPeriodId)
      .executeTakeFirst();

    if (!accountingPeriod) {
      return err(new AccountingPeriodNotFoundError(input.accountingPeriodId));
    }
  }

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

  if (input.companyId) {
    query = query.where("companyId", "=", input.companyId);
  }
  if (input.type) {
    query = query.where("allocationType", "=", input.type as AllocationCycleAllocationType);
  }
  if (input.status) {
    query = query.where("status", "=", input.status as AllocationCycleStatus);
  }
  if (input.accountingPeriodId) {
    query = query.where("accountingPeriodId", "=", input.accountingPeriodId);
  }

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

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