<?php

namespace App\Services;

use App\Mail\NewsletterMail;
use App\Models\Newsletter;
use App\Models\NewsletterSubscriber;
use Illuminate\Support\Facades\Cache;

class NewsletterSchedulerService
{
    protected const CACHE_KEY = 'newsletter_scheduler_last_run';

    protected const THROTTLE_SECONDS = 60;

    public function __construct(
        protected MailService $mailService
    ) {}

    /**
     * Envoie les campagnes programmées dont la date est dépassée.
     * Throttlé à une exécution par minute pour éviter les appels répétés.
     */
    public function sendDueCampaigns(): int
    {
        if (! $this->mailService->isConfigured()) {
            return 0;
        }

        if (Cache::has(self::CACHE_KEY)) {
            return 0;
        }

        Cache::put(self::CACHE_KEY, now(), self::THROTTLE_SECONDS);

        $due = Newsletter::whereNotNull('scheduled_at')
            ->whereNull('sent_at')
            ->where('scheduled_at', '<=', now())
            ->get();

        $sent = 0;

        foreach ($due as $newsletter) {
            $subscribers = NewsletterSubscriber::where('is_active', true)->get();
            $count = 0;

            foreach ($subscribers as $subscriber) {
                $mailable = new NewsletterMail(
                    $newsletter->subject,
                    $newsletter->content,
                    $subscriber->email,
                    $subscriber->name
                );
                if ($this->mailService->send($mailable)) {
                    $count++;
                }
            }

            $newsletter->update([
                'sent_at' => now(),
                'recipients_count' => $count,
            ]);

            $sent++;
        }

        return $sent;
    }
}
