<?php

namespace Tests\Feature;

use App\Models\Course;
use Database\Seeders\AcademyImportSeeder;
use Database\Seeders\CourseSeeder;
use Database\Seeders\MiniCoursesSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AcademyImportTest extends TestCase
{
    use RefreshDatabase;

    public function test_imports_real_investable_structure_with_wistia_videos(): void
    {
        $this->seed(CourseSeeder::class);       // creates 'investable' + catalogue
        $this->seed(MiniCoursesSeeder::class);  // creates the 5 mini-courses
        $this->seed(AcademyImportSeeder::class);

        $inv = Course::where('slug', 'investable')->first();
        $this->assertSame(5, $inv->modules()->count(), 'Investable should have 5 chapters');
        $this->assertSame(14, $inv->lessons()->count(), 'Investable should have 14 topic-lessons');
        $this->assertSame(12, $inv->lessons()->whereNotNull('video_url')->count(), '12 topics carry a Wistia video');

        $lesson = $inv->lessons()->whereNotNull('video_url')->first();
        $this->assertStringContainsString('wistia', $lesson->video_url);
        $this->assertStringContainsString('fast.wistia.net/embed/iframe/', $lesson->videoEmbedUrl());

        // Body text + downloadable materials imported (requires the extracted dataset).
        if (is_file(storage_path('app/academy-import/import2.json'))) {
            $this->assertGreaterThan(0, $inv->lessons()->whereNotNull('body')->count(), 'some lessons should have body text');
            $this->assertGreaterThan(0, $inv->lessons()->whereNotNull('materials')->count(), 'some lessons should have downloads');

            $worksheetHosted = $inv->lessons->contains(
                fn ($l) => collect($l->materials ?? [])->contains(
                    fn ($m) => str_contains($m['url'], '/academy/Investable_Wealth_Management_Worksheet')
                )
            );
            $this->assertTrue($worksheetHosted, 'the worksheet should be re-hosted under /academy/');
        }
    }

    public function test_mini_courses_get_their_real_video_lesson(): void
    {
        $this->seed(MiniCoursesSeeder::class);
        $this->seed(AcademyImportSeeder::class);

        foreach (['crypto-basics', 'planning-for-retirement', 'retirement-benefits-options', 'analyzing-financial-statements', 'core-values-and-your-money'] as $slug) {
            $course = Course::where('slug', $slug)->first();
            $this->assertNotNull($course, "$slug should exist");
            $videoLesson = $course->lessons()->whereNotNull('video_url')->first();
            $this->assertNotNull($videoLesson, "$slug should have a video lesson");
            $this->assertStringContainsString('fast.wistia.net/embed/iframe/', $videoLesson->videoEmbedUrl());
            $this->assertGreaterThan(0, $videoLesson->duration_minutes, "$slug video should have a runtime");
        }
    }
}
