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

type PeriodCloseOrderByField = "status" | "completionPercentage";

export interface ListPeriodClosesInput extends PaginationInput<PeriodCloseOrderByField> {
  companyId: string;
  fiscalYearId?: string;
  status?: string;
}

/**
 * Function: listPeriodCloses
 *
 * Lists period close records for a company. Since PeriodClose doesn't have a
 * direct companyId, a subquery through AccountingPeriod is used to filter by
 * company and optionally by fiscal year. Results are sorted by the associated
 * accounting period's startDate ascending by default.
 */
export async function run(db: ReadonlyDB<DB>, input: ListPeriodClosesInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderDirection = input.orderDirection ?? "asc";

  let periodSubquery = db
    .selectFrom("AccountingPeriod")
    .select("id")
    .where("companyId", "=", input.companyId);

  if (input.fiscalYearId) {
    periodSubquery = periodSubquery.where("fiscalYearId", "=", input.fiscalYearId);
  }

  let query = db
    .selectFrom("PeriodClose")
    .innerJoin("AccountingPeriod", "AccountingPeriod.id", "PeriodClose.accountingPeriodId")
    .selectAll("PeriodClose")
    .where("PeriodClose.accountingPeriodId", "in", periodSubquery);

  if (input.status) {
    query = query.where("PeriodClose.status", "=", input.status as PeriodCloseStatus);
  }

  // Default sort is by AccountingPeriod.startDate ascending per spec
  if (input.orderBy) {
    query = query.orderBy(`PeriodClose.${input.orderBy}` as never, orderDirection);
  } else {
    query = query.orderBy("AccountingPeriod.startDate", orderDirection);
  }

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

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