<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Services\CourseService;

class HomeController extends Controller
{
    public function index(): string
    {
        $courses = new CourseService();
        $allCourses = $courses->publicCourses();
        $homepageCourses = $this->homepageCourses($allCourses);
        $freeCourses = $this->homepageCourses($courses->publicCourses(['pricing' => 'free']));
        $paidCourses = $this->homepageCourses($courses->publicCourses(['pricing' => 'paid']));

        return $this->view('public/home', [
            'title' => 'Moz Cursos',
            'courses' => array_slice($homepageCourses, 0, 8),
            'featuredCourse' => $this->featuredCourse($homepageCourses),
            'freeCourses' => array_slice($freeCourses, 0, 8),
            'paidCourses' => array_slice($paidCourses, 0, 8),
            'courseStats' => [
                'total' => count($allCourses),
                'free' => count($freeCourses),
                'paid' => count($paidCourses),
                'students' => array_sum(array_map(fn (array $course): int => (int) ($course['students_count'] ?? 0), $allCourses)),
            ],
            'categories' => $courses->categories(true),
        ]);
    }

    public function health(): string
    {
        return 'OK';
    }

    private function homepageCourses(array $courses): array
    {
        $qualityCourses = array_values(array_filter($courses, function (array $course): bool {
            $title = strtolower((string) ($course['title'] ?? ''));
            $looksTemporary = str_contains($title, 'teste') || preg_match('/\d{6,}/', $title) === 1;
            $hasUsefulCopy = strlen(trim((string) ($course['subtitle'] ?? ''))) >= 18
                && strlen(trim((string) ($course['description'] ?? ''))) >= 50;

            return !$looksTemporary && $hasUsefulCopy;
        }));

        $ranked = $qualityCourses ?: $courses;
        usort($ranked, fn (array $a, array $b): int => $this->courseScore($b) <=> $this->courseScore($a));

        return array_values($ranked);
    }

    private function featuredCourse(array $courses): ?array
    {
        return $courses[0] ?? null;
    }

    private function courseScore(array $course): int
    {
        return (!empty($course['is_featured']) ? 1000 : 0)
            + (!empty($course['certificate_enabled']) ? 120 : 0)
            + ((int) ($course['students_count'] ?? 0))
            + ((int) round(((float) ($course['rating'] ?? 0)) * 40))
            + ((int) ($course['reviews_count'] ?? 0) * 2);
    }
}
