<?php

declare(strict_types=1);

namespace App\Http\Controllers\Academy;

use App\Http\Controllers\Controller;
use App\Models\AcademyChallenge;
use App\Models\AcademyCourse;
use App\Models\AcademyLesson;
use App\Models\AcademyPromptTemplate;
use App\Services\Academy\AcademyAccessService;
use App\Services\Academy\AcademyCacheService;
use App\Support\AcademyAnalytics\AcademyAnalyticsContentType;
use App\Support\Seo\SeoFactory;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

final class AcademyHomeController extends Controller
{
    public function __construct(
        private readonly AcademyAccessService $access,
        private readonly AcademyCacheService $cache,
    ) {
    }

    public function index(Request $request): Response
    {
        abort_unless((bool) config('academy.enabled', true), 404);

        $canonical = route('academy.index');
        $seo = app(SeoFactory::class)
            ->collectionPage(
                'Skinbase AI Academy — Skinbase',
                'Learn AI-powered creativity for wallpapers, digital art, skins, news covers, and visual worlds inside Skinbase.',
                $canonical,
            )
            ->toArray();

        $seo['og_type'] = 'website';

        $home = $this->cache->homePayload(function (): array {
            return [
                'featuredLessons' => $this->cache->featuredLessons(),
                'featuredCourses' => $this->cache->featuredCourses(),
                'featuredPrompts' => $this->cache->featuredPrompts(),
                'featuredChallenges' => (bool) config('academy.challenges_enabled', true)
                    ? $this->cache->featuredChallenges()
                    : [],
                'lessonCount' => AcademyLesson::query()->active()->published()->count(),
                'courseCount' => AcademyCourse::query()->published()->count(),
                'promptCount' => AcademyPromptTemplate::query()->active()->published()->count(),
                'challengeCount' => (bool) config('academy.challenges_enabled', true)
                    ? AcademyChallenge::query()->publiclyVisible()->count()
                    : 0,
            ];
        });

        return Inertia::render('Academy/Index', [
            'seo' => $seo,
            'pricingUrl' => route('academy.pricing'),
            'academyAccess' => array_merge($this->access->accessSummary($request->user()), [
                'billingUrl' => $request->user() && (bool) config('academy_billing.enabled', false)
                    ? route('academy.billing.account')
                    : route('academy.pricing'),
            ]),
            'links' => [
                'lessons' => route('academy.lessons.index'),
                'courses' => route('academy.courses.index'),
                'prompts' => route('academy.prompts.index'),
                'promptPopular' => route('academy.prompts.popular'),
                'packs' => route('academy.packs.index'),
                'challenges' => route('academy.challenges.index'),
            ],
            'featureFlags' => [
                'paymentsEnabled' => (bool) config('academy.payments_enabled', false),
                'challengesEnabled' => (bool) config('academy.challenges_enabled', true),
                'badgesEnabled' => (bool) config('academy.badges_enabled', true),
            ],
            'stats' => [
                'lessonCount' => (int) $home['lessonCount'],
                'courseCount' => (int) $home['courseCount'],
                'promptCount' => (int) $home['promptCount'],
                'challengeCount' => (int) $home['challengeCount'],
            ],
            'featuredCourses' => collect($home['featuredCourses'])->map(fn (AcademyCourse $course): array => $this->access->coursePayload($course, $request->user()))->values()->all(),
            'featuredLessons' => collect($home['featuredLessons'])->map(fn (AcademyLesson $lesson): array => $this->access->lessonPayload($lesson, $request->user()))->values()->all(),
            'featuredPrompts' => collect($home['featuredPrompts'])->map(fn (AcademyPromptTemplate $prompt): array => $this->access->promptPayload($prompt, $request->user()))->values()->all(),
            'featuredChallenges' => collect($home['featuredChallenges'])->map(fn (AcademyChallenge $challenge): array => $this->access->challengePayload($challenge, $request->user(), true))->values()->all(),
            'analytics' => [
                'enabled' => true,
                'contentType' => AcademyAnalyticsContentType::HOME,
                'contentId' => null,
                'eventUrl' => route('academy.analytics.events.store'),
                'pageName' => 'academy_home',
                'isPremium' => false,
                'isGuest' => $request->user() === null,
                'isSubscriber' => $request->user()?->hasAcademyCreatorAccess() || $request->user()?->hasAcademyProAccess(),
            ],
        ])->rootView('collections');
    }
}