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

type AccountingPeriodOrderByField = "startDate" | "endDate" | "name" | "status" | "createdAt";

export interface ListAccountingPeriodsInput extends PaginationInput<AccountingPeriodOrderByField> {
  companyId?: string;
  fiscalYearId?: string;
  status?: string;
  periodType?: string;
}

/**
 * Function: listAccountingPeriods
 *
 * Lists accounting periods with optional filters for company, fiscal year,
 * status, and period type. At least one scoping parameter (companyId or
 * fiscalYearId) is required. All filters use AND logic.
 */
export async function run(db: ReadonlyDB<DB>, input: ListAccountingPeriodsInput) {
  if (!input.companyId && !input.fiscalYearId) {
    return err(new ScopeRequiredError("companyId or fiscalYearId"));
  }

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

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

  if (input.companyId) {
    query = query.where("companyId", "=", input.companyId);
  }
  if (input.fiscalYearId) {
    query = query.where("fiscalYearId", "=", input.fiscalYearId);
  }
  if (input.status) {
    query = query.where("status", "=", input.status as AccountingPeriodStatus);
  }
  if (input.periodType) {
    query = query.where("periodType", "=", input.periodType as AccountingPeriodPeriodType);
  }

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

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