<?php

namespace App\Services;

use App\Mail\RanchWeightAlertMail;
use App\Models\ConfiguracionEmpresa;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;

class RanchWeightAlertNotificationService
{
    public function __construct(
        private readonly WeightPerformanceReportService $weightPerformanceService,
    ) {}

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

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

        $recipients = $this->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 RanchWeightAlertMail($report));
            } catch (Throwable $e) {
                $errors[] = $email.': '.$e->getMessage();
                Log::warning('Ranch weight 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)."
                : 'Correo de prueba enviado (sin alertas activas).',
        ];
    }

    /**
     * @return list<string>
     */
    public function resolveRecipients(): array
    {
        $fromEnv = config('ranch.alert_emails', []);
        if ($fromEnv !== []) {
            return array_values(array_unique($fromEnv));
        }

        $empresaEmail = ConfiguracionEmpresa::obtenerConfiguracion()?->email;
        if ($empresaEmail && filter_var($empresaEmail, FILTER_VALIDATE_EMAIL)) {
            return [$empresaEmail];
        }

        $admins = User::role('Administrador')->pluck('email')->filter()->all();
        if ($admins !== []) {
            return array_values(array_unique($admins));
        }

        $fallback = config('mail.from.address');
        if ($fallback && filter_var($fallback, FILTER_VALIDATE_EMAIL)) {
            return [$fallback];
        }

        return [];
    }
}
