<?php

namespace App\Services;

use App\Models\Lead;
use App\Services\Lead\ProcessLeadCapturedService;
use App\Support\AfterResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class WebsiteContactLeadService
{
    public function __construct(
        private readonly LeadActivityService $activityService
    ) {
    }

    /**
     * @param  array{name: string, email: string, phone: string, subject: string, message: string}  $data
     */
    public function createFromContactForm(array $data): Lead
    {
        $mobile = $this->normalizeMobile($data['phone']);

        if (Lead::where('mobile', $mobile)->whereIn('status', ['new', 'contacted', 'qualified', 'meeting_scheduled'])->exists()) {
            throw ValidationException::withMessages([
                'phone' => 'A lead with this mobile number already exists and is being followed up.',
            ]);
        }

        return DB::transaction(function () use ($data, $mobile): Lead {
            $lead = Lead::create([
                'company_name' => 'Website Contact',
                'contact_person_name' => $data['name'],
                'mobile' => $mobile,
                'email' => $data['email'],
                'employee_count' => 0,
                'source' => 'website_contact',
                'status' => 'new',
                'notes' => $this->buildNotes($data),
            ]);

            $this->activityService->log($lead, 'captured', 'Lead captured from contact page', [
                'source' => 'website_contact',
                'subject' => $data['subject'],
            ]);

            AfterResponse::run(fn () => app(ProcessLeadCapturedService::class)->handle($lead->id));

            return $lead;
        });
    }

    /**
     * @param  array{subject: string, message: string}  $data
     */
    private function buildNotes(array $data): string
    {
        return trim('Subject: ' . $data['subject'] . PHP_EOL . PHP_EOL . $data['message']);
    }

    private function normalizeMobile(string $mobile): string
    {
        return preg_replace('/\D+/', '', $mobile) ?? $mobile;
    }
}
