import type { AppState } from '@domain/ports/StateRepository';
import { elapsed } from '@domain/services/GaugeCalculator';

export interface DashboardQuery { type: 'get-dashboard'; }

export interface EnclosSummary {
  id: number;
  name: string;
  ddCount: number;
  running: boolean;
  elapsedSec: number;
  activeGauges: string[];
}

export interface DashboardResult {
  enclosSummaries: EnclosSummary[];
  totalCouples: number;
  totalBabies: number;
  raceBreakdown: Record<string, number>;
  successRate: number;
}

export function createGetDashboardHandler(state: AppState) {
  return (_query: DashboardQuery): DashboardResult => {
    const summaries: EnclosSummary[] = state.enclos.map(enc => ({
      id: enc.id,
      name: enc.name,
      ddCount: enc.dragodindes.length,
      running: enc.timer.running,
      elapsedSec: elapsed(enc.timer),
      activeGauges: [...enc.activeGauges],
    }));

    let totalCouples = 0, totalBabies = 0;
    const raceBreakdown: Record<string, number> = {};

    // From accouplements
    for (const acc of state.accouplements) {
      totalCouples += acc.couples;
      totalBabies += acc.babiesObtained;
      raceBreakdown[acc.baby] = (raceBreakdown[acc.baby] ?? 0) + acc.babiesObtained;
    }

    // From archived stats (legacy migration)
    for (const arch of state.archivedStats as Array<{ baby?: string; couples?: number; babiesObtained?: number }>) {
      if (arch.baby) {
        totalCouples += arch.couples ?? 0;
        totalBabies += arch.babiesObtained ?? 0;
        raceBreakdown[arch.baby] = (raceBreakdown[arch.baby] ?? 0) + (arch.babiesObtained ?? 0);
      }
    }

    const successRate = totalCouples > 0 ? Math.round((totalBabies / totalCouples) * 100) : 0;

    return { enclosSummaries: summaries, totalCouples, totalBabies, raceBreakdown, successRate };
  };
}
