<?php

namespace Tests\Feature;

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

class PdfReportTest extends TestCase
{
    use RefreshDatabase;

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

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

        Livewire::test(AssessmentRunner::class, ['assessment' => $assessment])
            ->call('submit', $answers, 'Test User', 'pdf@example.com');

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

    public function test_dimension_assessment_pdf_renders_with_svg_visuals(): void
    {
        $this->seed(FinancialHealthSeeder::class);
        $attempt = $this->complete('financial-health');

        $res = $this->get(route('assessments.results.pdf', [
            'assessment' => $attempt->assessment->slug,
            'attempt' => $attempt->uuid,
        ]));

        $res->assertOk()->assertHeader('content-type', 'application/pdf');
        $this->assertStringStartsWith('%PDF', $res->getContent());
    }

    public function test_profile_assessment_pdf_renders(): void
    {
        $this->seed(MoneyPersonalitySeeder::class);
        $attempt = $this->complete('money-personality');

        $this->get(route('assessments.results.pdf', [
            'assessment' => $attempt->assessment->slug,
            'attempt' => $attempt->uuid,
        ]))->assertOk()->assertHeader('content-type', 'application/pdf');
    }

    public function test_tool_pdf_embeds_chart_image(): void
    {
        $png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC';

        $this->post('/tools/budget/pdf', [
            'currency' => 'USD',
            'chart' => $png,
            'chartTitle' => 'Where your money goes',
            'sections' => [['title' => 'Income', 'rows' => [['Take-home', '$800']]]],
        ])->assertOk()->assertHeader('content-type', 'application/pdf');
    }

    public function test_tool_pdf_rejects_non_image_chart(): void
    {
        $this->postJson('/tools/budget/pdf', [
            'chart' => 'not-an-image',
            'sections' => [['title' => 'Income', 'rows' => [['Take-home', '$800']]]],
        ])->assertStatus(422);
    }
}
