<?php

namespace Tests\Feature;

use App\Livewire\AssessmentRunner;
use App\Models\Assessment;
use App\Models\AssessmentAttempt;
use App\Models\Campaign;
use App\Models\User;
use Database\Seeders\FinancialHealthSeeder;
use Database\Seeders\RolesAndAdminSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class CampaignTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(RolesAndAdminSeeder::class);
        $this->seed(FinancialHealthSeeder::class);
    }

    private function completeWithCampaign(?string $campaign, string $email): AssessmentAttempt
    {
        $assessment = Assessment::where('slug', 'financial-health')->firstOrFail();
        $answers = $assessment->questions->mapWithKeys(fn ($q) => [$q->id => $q->options[0]['key']])->all();

        Livewire::withQueryParams($campaign ? ['campaign' => $campaign] : [])
            ->test(AssessmentRunner::class, ['assessment' => $assessment])
            ->call('submit', $answers, 'Tester', $email);

        return AssessmentAttempt::latest('id')->firstOrFail();
    }

    public function test_active_campaign_tags_attempt_and_lead(): void
    {
        Campaign::create(['name' => 'Acme staff', 'slug' => 'acme', 'assessment' => 'financial-health', 'is_active' => true]);

        $attempt = $this->completeWithCampaign('acme', 'acme@example.com');

        $this->assertSame('acme', $attempt->campaign);
        $this->assertDatabaseHas('leads', ['email' => 'acme@example.com', 'segment' => 'acme']);
        $this->assertSame(1, Campaign::where('slug', 'acme')->first()->leads_count);
    }

    public function test_inactive_or_unknown_campaign_is_ignored(): void
    {
        Campaign::create(['name' => 'Old', 'slug' => 'old', 'assessment' => 'financial-health', 'is_active' => false]);

        $this->assertNull($this->completeWithCampaign('old', 'old@example.com')->campaign);
        $this->assertNull($this->completeWithCampaign('does-not-exist', 'nope@example.com')->campaign);
    }

    public function test_share_url(): void
    {
        $campaign = Campaign::create(['name' => 'X', 'slug' => 'x', 'assessment' => 'financial-health', 'is_active' => true]);
        $this->assertStringContainsString('/assessments/financial-health?campaign=x', $campaign->shareUrl());
    }

    public function test_campaign_admin_pages_render(): void
    {
        $admin = User::where('email', 'admin@moneywise.co.ke')->firstOrFail();
        $this->actingAs($admin);

        $this->get('/admin/campaigns')->assertSuccessful();
        $this->get('/admin/campaigns/create')->assertSuccessful();
    }
}
