<?php

namespace App\Jobs;

use App\Models\Lead;
use App\Models\LeadFollowup;
use App\Models\User;
use App\Notifications\NewLeadCapturedNotification;
use App\Services\LeadActivityService;
use App\Services\Messaging\Fast2SmsService;
use App\Services\Messaging\WhatsAppService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessLeadCapturedJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public int $leadId)
    {
    }

    public function handle(
        LeadActivityService $activityService,
        Fast2SmsService $smsService,
        WhatsAppService $whatsAppService
    ): void {
        $lead = Lead::find($this->leadId);
        if (! $lead) {
            return;
        }

        $superAdmins = User::where('is_superadmin', true)->get();
        foreach ($superAdmins as $admin) {
            $admin->notify(new NewLeadCapturedNotification($lead));
        }
        $activityService->log($lead, 'superadmin_notified', 'Super admin team notified for new lead');

        $followupAt = now()->addMinutes((int) config('lead.followup.initial_delay_minutes', 30));
        $followup = LeadFollowup::create([
            'lead_id' => $lead->id,
            'followup_at' => $followupAt,
            'status' => 'pending',
            'channel' => 'call',
            'message' => $lead->source === 'website_contact'
                ? 'Initial follow-up after contact form submission.'
                : 'Initial follow-up after registration.',
        ]);

        $lead->update(['next_followup_at' => $followup->followup_at]);
        $activityService->log($lead, 'followup_created', 'Initial follow-up created', [
            'followup_id' => $followup->id,
        ]);

        $ackTemplate = (string) config('lead.fast2sms.ack_template');
        $ackMessage = str_replace('{{name}}', $lead->contact_person_name, $ackTemplate);
        if ($smsService->sendMessage($lead->mobile, $ackMessage)) {
            $activityService->log($lead, 'sms_sent', 'Acknowledgement SMS sent to lead');
        }

        if ($whatsAppService->sendTemplate($lead->mobile, config('lead.whatsapp.template_new_lead'), [
            'name' => $lead->contact_person_name,
        ])) {
            $activityService->log($lead, 'whatsapp_sent', 'Initial WhatsApp message sent to lead');
        }
    }
}
