<?php

declare(strict_types=1);

namespace App\Services\Academy;

use App\Models\AcademyChallenge;
use App\Models\AcademyCourse;
use App\Models\AcademyLesson;
use App\Models\AcademyPromptPack;
use App\Models\AcademyPromptTemplate;
use App\Support\AcademyAnalytics\AcademyAnalyticsContentType;
use Illuminate\Database\Eloquent\Model;

final class AcademyAnalyticsContentResolver
{
    public function resolve(string $contentType, int $contentId): ?Model
    {
        $modelClass = match ($contentType) {
            AcademyAnalyticsContentType::PROMPT => AcademyPromptTemplate::class,
            AcademyAnalyticsContentType::LESSON => AcademyLesson::class,
            AcademyAnalyticsContentType::COURSE => AcademyCourse::class,
            AcademyAnalyticsContentType::PROMPT_PACK => AcademyPromptPack::class,
            AcademyAnalyticsContentType::CHALLENGE => AcademyChallenge::class,
            default => null,
        };

        if ($modelClass === null) {
            return null;
        }

        return $modelClass::query()->find($contentId);
    }

    public function exists(string $contentType, int $contentId): bool
    {
        return $this->resolve($contentType, $contentId) instanceof Model;
    }

    public function title(string $contentType, ?int $contentId): string
    {
        if (! $contentId) {
            return match ($contentType) {
                AcademyAnalyticsContentType::HOME => 'Academy Home',
                AcademyAnalyticsContentType::PROMPT_LIBRARY => 'Prompt Library',
                AcademyAnalyticsContentType::PROMPT_POPULAR => 'Popular Prompts',
                AcademyAnalyticsContentType::PROMPT_PACK_LIBRARY => 'Prompt Pack Library',
                AcademyAnalyticsContentType::SEARCH => 'Academy Search',
                AcademyAnalyticsContentType::UPGRADE => 'Academy Upgrade',
                default => 'Unknown Academy Content',
            };
        }

        $content = $this->resolve($contentType, $contentId);

        if (! $content instanceof Model) {
            return 'Unknown Academy Content';
        }

        return (string) ($content->title ?? $content->name ?? sprintf('%s #%d', $contentType, $contentId));
    }

    public function accessLevel(string $contentType, ?int $contentId): ?string
    {
        if (! $contentId) {
            return null;
        }

        $content = $this->resolve($contentType, $contentId);

        return $content instanceof Model ? (string) ($content->access_level ?? '') : null;
    }
}