<?php

namespace App\Services;

class RanchAlertCenterService
{
    public function __construct(
        private readonly WeightPerformanceReportService $weightPerformanceService,
        private readonly RanchActiveCostAlertService $activeCostAlertService,
        private readonly RanchHealthReportService $healthReportService,
        private readonly RanchMotherPerformanceService $motherPerformanceService,
        private readonly RanchOpenLotsGdpAlertService $openLotsGdpAlertService,
    ) {}

    /**
     * @return array<string, mixed>
     */
    public function generate(): array
    {
        $weight = $this->weightPerformanceService->generate();
        $cost = $this->activeCostAlertService->generate();
        $atRiskMothers = $this->healthReportService->mothersWithSickOffspring();
        $motherReport = $this->motherPerformanceService->generate();

        $gdpLots = $this->openLotsGdpAlertService->generate();

        $motherAlerts = collect($motherReport['mothers'])
            ->filter(fn ($row) => ($row['high_mortality_risk'] ?? false) || ($row['health_risk'] ?? false))
            ->values()
            ->map(fn ($row) => [
                'mother_id' => $row['mother_id'],
                'ear_tag' => $row['ear_tag'],
                'offspring_count' => $row['offspring_count'],
                'mortality_rate_pct' => $row['mortality_rate_pct'],
                'offspring_illness_events' => $row['offspring_illness_events'],
                'alert_message' => $this->motherAlertMessage($row),
            ])
            ->all();

        $sections = [
            [
                'key' => 'weight',
                'title' => 'Rendimiento de peso (GDP)',
                'count' => (int) ($weight['alert_count'] ?? 0),
                'route' => '/ganaderia/rendimiento-peso',
                'items' => $weight['alerts'] ?? [],
            ],
            [
                'key' => 'cost',
                'title' => 'Costo por kg (activos)',
                'count' => (int) ($cost['alert_count'] ?? 0),
                'route' => '/ganaderia/alertas-costo',
                'items' => $cost['alerts'] ?? [],
            ],
            [
                'key' => 'mothers_health',
                'title' => 'Vacas — enfermedades en crías',
                'count' => count($atRiskMothers),
                'route' => '/ganaderia/vacas-madre',
                'items' => $atRiskMothers,
            ],
            [
                'key' => 'mothers_performance',
                'title' => 'Vacas — mortalidad o riesgo salud',
                'count' => count($motherAlerts),
                'route' => '/ganaderia/vacas-madre',
                'items' => $motherAlerts,
            ],
            [
                'key' => 'open_lots_gdp',
                'title' => 'Engorda abierta — GDP bajo meta',
                'count' => (int) ($gdpLots['lots_with_alerts_count'] ?? 0),
                'route' => '/ganaderia/engorda-proyeccion',
                'items' => $gdpLots['lots_with_alerts'] ?? [],
            ],
        ];

        $totalCount = array_sum(array_column($sections, 'count'));

        return [
            'total_count' => $totalCount,
            'sections' => $sections,
            'generated_at' => now()->toIso8601String(),
        ];
    }

    /**
     * @param  array<string, mixed>  $row
     */
    private function motherAlertMessage(array $row): string
    {
        $parts = [];
        if ($row['high_mortality_risk'] ?? false) {
            $parts[] = 'Mortalidad progenie '.$row['mortality_rate_pct'].'%';
        }
        if ($row['health_risk'] ?? false) {
            $parts[] = $row['offspring_illness_events'].' eventos de enfermedad en crías';
        }

        return implode(' · ', $parts);
    }
}
