// apps/web/src/server/referrals/maturation.ts
import type { DrizzleClient, TxDrizzleClient } from '@/server/db/client';
import { createMaturityHostStore } from '@/server/affiliate-module/maturity-host-store.js';
import { sweepMaturationDriver } from '@/server/affiliate-module/sweep-driver.js';

type MatureAtInput = {
  kind: 'coupon' | 'physical' | string;
  paidAt: Date;
  expiresAt: Date | null;
  redeemedAt: Date | null;
};

type MatureAtSettings = { holdDays: number };

/**
 * Compute the mature_at timestamp for a credit ledger entry.
 *
 * - physical deal: paidAt + holdDays
 * - coupon (redeemed): redeemedAt + holdDays
 * - coupon (not yet redeemed): max(paidAt, expiresAt) + holdDays
 */
export function computeMatureAt(input: MatureAtInput, settings: MatureAtSettings): Date {
  const holdMs = settings.holdDays * 86400_000;

  if (input.kind === 'coupon') {
    if (input.redeemedAt) {
      return new Date(input.redeemedAt.getTime() + holdMs);
    }
    const anchor = input.expiresAt
      ? new Date(Math.max(input.paidAt.getTime(), input.expiresAt.getTime()))
      : input.paidAt;
    return new Date(anchor.getTime() + holdMs);
  }

  return new Date(input.paidAt.getTime() + holdMs);
}

export type SweepResult = { promoted: number; recomputed: number; sweptAt: Date };

/**
 * Maturation sweep: promotes pending ledger_entry_vesting rows to matured.
 *
 * Live path — delegates to sweepMaturationDriver + MaturityHostStore injection.
 * Called every 30-min tick from /api/internal/maturation/sweep via the DO worker.
 */
export async function sweepMaturation(db: DrizzleClient): Promise<SweepResult> {
  return sweepMaturationDriver(db as TxDrizzleClient, createMaturityHostStore(db));
}

/** Alias for callers using the runMaturationSweep name. */
export const runMaturationSweep = sweepMaturation;
