<?php

namespace Tests\Feature;

use App\Models\Lead;
use App\Models\LeadFollowup;
use App\Models\LeadOtpVerification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;

class LeadCaptureTest extends TestCase
{
    use RefreshDatabase;

    public function test_register_submission_requires_verified_otp(): void
    {
        $response = $this->post('/register', [
            'company_name' => 'Acme Pvt Ltd',
            'contact_person_name' => 'John Doe',
            'mobile' => '9876543210',
            'employee_count' => 50,
        ]);

        $response->assertSessionHasErrors(['mobile']);
        $this->assertDatabaseCount('leads', 0);
    }

    public function test_verified_otp_allows_lead_creation(): void
    {
        LeadOtpVerification::create([
            'mobile' => '9876543210',
            'otp_hash' => Hash::make('123456'),
            'expires_at' => now()->addMinutes(10),
            'verified_at' => now(),
        ]);

        $response = $this->post('/register', [
            'company_name' => 'Acme Pvt Ltd',
            'contact_person_name' => 'John Doe',
            'mobile' => '9876543210',
            'employee_count' => 50,
            'email' => 'john@acme.test',
        ]);

        $response->assertRedirect(route('register'));
        $this->assertDatabaseHas('leads', [
            'company_name' => 'Acme Pvt Ltd',
            'mobile' => '9876543210',
            'employee_count' => 50,
        ]);

        $lead = Lead::where('mobile', '9876543210')->firstOrFail();
        $this->assertDatabaseHas('lead_followups', [
            'lead_id' => $lead->id,
            'status' => 'pending',
        ]);
        $this->assertNotNull(LeadFollowup::where('lead_id', $lead->id)->value('followup_at'));
    }

    public function test_otp_verify_endpoint_marks_mobile_as_verified(): void
    {
        LeadOtpVerification::create([
            'mobile' => '9876543210',
            'otp_hash' => Hash::make('123456'),
            'expires_at' => now()->addMinutes(10),
        ]);

        $response = $this->postJson(route('register.otp.verify'), [
            'mobile' => '9876543210',
            'otp' => '123456',
        ]);

        $response->assertOk();
        $this->assertNotNull(LeadOtpVerification::where('mobile', '9876543210')->value('verified_at'));
    }
}
