<?php

namespace Tests\Feature;

use App\Models\Guide;
use Database\Seeders\GuideSeeder;
use Database\Seeders\PostSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LibraryTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        $this->seed(GuideSeeder::class);
        $this->seed(PostSeeder::class);
    }

    public function test_resources_index_renders_with_guides(): void
    {
        $this->get('/resources')
            ->assertOk()
            ->assertSee('The Debt-Free Playbook')
            ->assertSee('Your First Investment');
    }

    public function test_resources_search_filters_guides(): void
    {
        $this->get('/resources?q=chama')
            ->assertOk()
            ->assertSee('Group Investing Starter Kit')
            ->assertDontSee('The Debt-Free Playbook');
    }

    public function test_resources_category_filter_works(): void
    {
        $this->get('/resources?category=Debt')
            ->assertOk()
            ->assertSee('The Debt-Free Playbook')
            ->assertDontSee('Your First Investment');
    }

    public function test_flipbook_reader_renders_pages(): void
    {
        $this->get('/resources/debt-free-playbook')
            ->assertOk()
            ->assertSee('Open the book')
            ->assertSee('Face the number');
    }

    public function test_guide_pdf_downloads_and_counts(): void
    {
        $response = $this->get('/resources/debt-free-playbook/pdf');

        $response->assertOk();
        $this->assertSame('application/pdf', $response->headers->get('content-type'));
        $this->assertSame(1, Guide::where('slug', 'debt-free-playbook')->first()->download_count);
    }

    public function test_blog_search_and_category_filter(): void
    {
        $this->get('/blog?q=resilience')
            ->assertOk()
            ->assertSee('Building Financial Resilience');

        $this->get('/blog?category=Family')
            ->assertOk()
            ->assertSee('My Partner and I')
            ->assertDontSee('Six Money Habits');
    }

    public function test_new_calculator_tools_render(): void
    {
        $this->get('/tools/loan-cost')->assertOk()->assertSee('True Cost of a Loan');
        $this->get('/tools/retirement')->assertOk()->assertSee('Retirement Readiness');
    }

    public function test_tool_pdf_endpoint_returns_pdf(): void
    {
        $response = $this->postJson('/tools/loan-cost/pdf', [
            'currency' => 'KES',
            'highlight' => ['value' => 'KSh 250,000', 'label' => 'True total cost'],
            'sections' => [
                ['title' => 'The loan', 'rows' => [['Amount', 'KSh 200,000'], ['Rate', '18%']]],
            ],
            'note' => 'Test note',
        ]);

        $response->assertOk();
        $this->assertSame('application/pdf', $response->headers->get('content-type'));
    }
}
