<?php

namespace App\Services;

class RanchActiveCostAlertService
{
    public function __construct(
        private readonly RanchAnimalProfitabilityService $profitabilityService,
    ) {}

    /**
     * Animales activos con costo acumulado por kg ganado por encima del umbral.
     *
     * @return array<string, mixed>
     */
    public function generate(?float $maxCostPerKg = null, ?float $minWeightGainKg = null): array
    {
        $maxCostPerKg ??= (float) config('ranch.profitability_alerts.max_cost_per_kg_active', 25);
        $minWeightGainKg ??= (float) config('ranch.profitability_alerts.min_weight_gain_kg', 30);

        $profitability = $this->profitabilityService->generate(null, null, 'active');
        $alerts = [];

        foreach ($profitability['animals'] as $row) {
            $gain = $row['weight_gain_kg'] ?? null;
            $costPerKg = $row['cost_per_kg_gained'] ?? null;

            if ($gain === null || $gain < $minWeightGainKg || $costPerKg === null) {
                continue;
            }

            if ($costPerKg > $maxCostPerKg) {
                $alerts[] = array_merge($row, [
                    'alert_type' => 'high_cost_per_kg',
                    'alert_message' => sprintf(
                        'Costo %.2f $/kg (umbral %.2f) con %.1f kg ganados',
                        $costPerKg,
                        $maxCostPerKg,
                        $gain
                    ),
                ]);
            }
        }

        usort($alerts, fn ($a, $b) => ($b['cost_per_kg_gained'] ?? 0) <=> ($a['cost_per_kg_gained'] ?? 0));

        return [
            'max_cost_per_kg' => $maxCostPerKg,
            'min_weight_gain_kg' => $minWeightGainKg,
            'alert_count' => count($alerts),
            'alerts' => $alerts,
        ];
    }
}
