<?php

namespace App\Services;

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

class RanchOpenLotsGdpAlertNotificationService
{
    public function __construct(
        private readonly RanchOpenLotsGdpAlertService $gdpAlertService,
        private readonly RanchWeightAlertNotificationService $recipientService,
    ) {}

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

        if ($lotsCount === 0 && ! $force) {
            return [
                'sent' => false,
                'lots_with_alerts_count' => 0,
                'animal_alerts_count' => $animalCount,
                'recipients' => [],
                'message' => 'No hay lotes de engorda con alertas GDP; no se envió correo.',
            ];
        }

        $recipients = $this->recipientService->resolveRecipients();
        if ($recipients === []) {
            return [
                'sent' => false,
                'lots_with_alerts_count' => $lotsCount,
                'animal_alerts_count' => $animalCount,
                'recipients' => [],
                'message' => 'No hay destinatarios configurados (RANCH_ALERT_EMAILS o administradores).',
            ];
        }

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

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

        return [
            'sent' => true,
            'lots_with_alerts_count' => $lotsCount,
            'animal_alerts_count' => $animalCount,
            'recipients' => $recipients,
            'message' => $lotsCount > 0
                ? "Correo enviado: {$lotsCount} lote(s), {$animalCount} animal(es) en alerta."
                : 'Correo de prueba enviado (sin alertas en engorda).',
        ];
    }
}
