<?php

namespace App\Services;

use App\Mail\RanchCostAlertMail;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;

class RanchCostAlertNotificationService
{
    public function __construct(
        private readonly RanchActiveCostAlertService $costAlertService,
        private readonly RanchWeightAlertNotificationService $recipientResolver,
    ) {}

    /**
     * @return array{sent: bool, alert_count: int, recipients: list<string>, message: string}
     */
    public function sendIfNeeded(?float $maxCostPerKg = null, ?float $minWeightGainKg = null, bool $force = false): array
    {
        $report = $this->costAlertService->generate($maxCostPerKg, $minWeightGainKg);
        $alertCount = (int) ($report['alert_count'] ?? 0);

        if ($alertCount === 0 && ! $force) {
            return [
                'sent' => false,
                'alert_count' => 0,
                'recipients' => [],
                'message' => 'No hay alertas de costo/kg; no se envió correo.',
            ];
        }

        $recipients = $this->recipientResolver->resolveRecipients();
        if ($recipients === []) {
            return [
                'sent' => false,
                'alert_count' => $alertCount,
                'recipients' => [],
                'message' => 'No hay destinatarios configurados (RANCH_ALERT_EMAILS o administradores).',
            ];
        }

        $errors = [];
        foreach ($recipients as $email) {
            try {
                Mail::to($email)->send(new RanchCostAlertMail($report));
            } catch (Throwable $e) {
                $errors[] = $email.': '.$e->getMessage();
                Log::warning('Ranch cost alert email failed', [
                    'destinatario' => $email,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        if ($errors !== [] && count($errors) === count($recipients)) {
            return [
                'sent' => false,
                'alert_count' => $alertCount,
                'recipients' => $recipients,
                'message' => 'Falló el envío a todos los destinatarios.',
            ];
        }

        return [
            'sent' => true,
            'alert_count' => $alertCount,
            'recipients' => $recipients,
            'message' => $alertCount > 0
                ? "Correo enviado con {$alertCount} alerta(s) de costo/kg."
                : 'Correo de prueba enviado (sin alertas activas).',
        ];
    }
}
