<?php

namespace App\Services\Lead;

use App\Models\LeadFollowup;
use App\Models\User;
use App\Notifications\LeadUpcomingActivityNotification;
use App\Services\LeadActivityService;
use App\Services\Messaging\Fast2SmsService;
use App\Services\Messaging\WhatsAppService;

class SendDueLeadFollowupRemindersService
{
    public function __construct(
        private readonly Fast2SmsService $smsService,
        private readonly WhatsAppService $whatsAppService,
        private readonly LeadActivityService $activityService,
    ) {}

    public function handle(): int
    {
        $dueFollowups = LeadFollowup::with('lead')
            ->where('status', 'pending')
            ->whereNull('reminder_sent_at')
            ->where('followup_at', '<=', now())
            ->limit(100)
            ->get();

        $processed = 0;

        foreach ($dueFollowups as $followup) {
            $lead = $followup->lead;
            if (! $lead) {
                continue;
            }

            $template = (string) config('lead.fast2sms.followup_template');
            $message = str_replace('{{name}}', $lead->contact_person_name, $template);

            if ($this->smsService->sendMessage($lead->mobile, $message)) {
                $this->activityService->log($lead, 'followup_sms_sent', 'Follow-up SMS reminder sent', [
                    'followup_id' => $followup->id,
                ]);
            }

            if ($this->whatsAppService->sendTemplate($lead->mobile, config('lead.whatsapp.template_followup'), [
                'name' => $lead->contact_person_name,
            ])) {
                $this->activityService->log($lead, 'followup_whatsapp_sent', 'Follow-up WhatsApp reminder sent', [
                    'followup_id' => $followup->id,
                ]);
            }

            $superAdmins = User::where('is_superadmin', true)->get();
            foreach ($superAdmins as $admin) {
                $admin->notify(new LeadUpcomingActivityNotification($lead, $followup));
            }

            $followup->update(['reminder_sent_at' => now()]);
            $processed++;
        }

        return $processed;
    }
}
