<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\FileStore;

class CourseService
{
    private FileStore $courses;
    private FileStore $categories;
    private FileStore $sections;
    private FileStore $lessons;
    private AuthService $auth;
    private ActivityLogService $logs;

    public function __construct()
    {
        $this->courses = new FileStore(storage_path('data/courses.json'));
        $this->categories = new FileStore(storage_path('data/categories.json'));
        $this->sections = new FileStore(storage_path('data/course_sections.json'));
        $this->lessons = new FileStore(storage_path('data/lessons.json'));
        $this->auth = new AuthService();
        $this->logs = new ActivityLogService();

        $this->seedCategories();
        $this->seedCourses();
    }

    public function categories(bool $activeOnly = false): array
    {
        $categories = $this->categories->all();

        if ($activeOnly) {
            $categories = array_filter($categories, fn (array $category): bool => ($category['status'] ?? '') === 'active');
        }

        usort($categories, fn (array $a, array $b): int => strcmp($a['name'], $b['name']));

        return array_values($categories);
    }

    public function createCategory(array $data, int $adminId): array
    {
        $name = trim($data['name'] ?? '');

        if ($name === '') {
            return ['ok' => false, 'error' => 'O nome da categoria e obrigatorio.'];
        }

        $category = $this->categories->insert([
            'name' => $name,
            'slug' => $this->slug($name),
            'description' => trim($data['description'] ?? ''),
            'status' => 'active',
            'created_at' => date('c'),
            'updated_at' => date('c'),
        ]);

        $this->logs->log('category_created', "Categoria {$name} criada.", $adminId);

        return ['ok' => true, 'category' => $category];
    }

    public function publicCourses(array $filters = []): array
    {
        $courses = array_filter($this->courses->all(), fn (array $course): bool => ($course['status'] ?? '') === 'published');

        return $this->filterAndHydrate($courses, $filters);
    }

    public function adminCourses(array $filters = []): array
    {
        return $this->filterAndHydrate($this->courses->all(), $filters);
    }

    public function ownerCourses(int $ownerId, string $ownerRole, array $filters = []): array
    {
        $courses = array_filter($this->courses->all(), function (array $course) use ($ownerId, $ownerRole): bool {
            if ($ownerRole === 'admin') {
                return true;
            }

            return (int) ($course['owner_id'] ?? 0) === $ownerId;
        });

        return $this->filterAndHydrate($courses, $filters);
    }

    public function stats(): array
    {
        $stats = [
            'total' => 0,
            'draft' => 0,
            'submitted' => 0,
            'published' => 0,
            'rejected' => 0,
            'suspended' => 0,
            'free' => 0,
            'paid' => 0,
        ];

        foreach ($this->courses->all() as $course) {
            $stats['total']++;
            $status = $course['status'] ?? '';

            if (isset($stats[$status])) {
                $stats[$status]++;
            }

            if (!empty($course['is_free'])) {
                $stats['free']++;
            } else {
                $stats['paid']++;
            }
        }

        return $stats;
    }

    public function find(int $id): ?array
    {
        foreach ($this->courses->all() as $course) {
            if ((int) ($course['id'] ?? 0) === $id) {
                return $this->hydrate($course);
            }
        }

        return null;
    }

    public function create(array $data, array $user): array
    {
        $errors = $this->validate($data);

        if ($errors) {
            return ['ok' => false, 'errors' => $errors];
        }

        $title = trim($data['title']);
        $isFree = ($data['pricing_type'] ?? 'paid') === 'free';
        $price = $isFree ? 0 : (float) str_replace(',', '.', (string) ($data['price'] ?? 0));
        $discountPrice = $this->discountPrice($data, $isFree, $price);

        $course = $this->courses->insert([
            'owner_type' => $this->ownerType($user),
            'owner_id' => (int) $user['id'],
            'category_id' => (int) $data['category_id'],
            'title' => $title,
            'slug' => $this->slug($title),
            'subtitle' => trim($data['subtitle'] ?? ''),
            'description' => trim($data['description'] ?? ''),
            'promo_video_url' => trim($data['promo_video_url'] ?? ''),
            'cover_image_url' => trim($data['cover_image_url'] ?? ''),
            'cover_color' => $data['cover_color'] ?? '#0f766e',
            'level' => $data['level'] ?? 'all',
            'language' => trim($data['language'] ?? 'Portugues'),
            'price' => $price,
            'discount_price' => $discountPrice,
            'currency' => 'MZN',
            'is_free' => $isFree,
            'is_featured' => !empty($data['is_featured']) && has_role('admin'),
            'access_type' => $data['access_type'] ?? 'lifetime',
            'access_duration_days' => (int) ($data['access_duration_days'] ?? 0),
            'certificate_enabled' => !empty($data['certificate_enabled']),
            'completion_percentage_required' => (int) ($data['completion_percentage_required'] ?? 100),
            'final_quiz_required' => !empty($data['final_quiz_required']),
            'final_quiz_pass_score' => max(1, (int) ($data['final_quiz_pass_score'] ?? 70)),
            'duration_minutes' => (int) ($data['duration_minutes'] ?? 0),
            'workload_hours' => (int) ($data['workload_hours'] ?? 0),
            'requirements' => trim($data['requirements'] ?? ''),
            'learning_outcomes' => trim($data['learning_outcomes'] ?? ''),
            'course_includes' => trim($data['course_includes'] ?? ''),
            'target_audience' => trim($data['target_audience'] ?? ''),
            'welcome_message' => trim($data['welcome_message'] ?? ''),
            'status' => 'draft',
            'rejection_reason' => '',
            'rating' => 0,
            'reviews_count' => 0,
            'students_count' => 0,
            'published_at' => null,
            'approved_at' => null,
            'approved_by' => null,
            'created_at' => date('c'),
            'updated_at' => date('c'),
        ]);

        $this->logs->log('course_created', "Curso {$title} criado.", (int) $user['id']);

        return ['ok' => true, 'course' => $course];
    }

    public function update(int $id, array $data, array $user): array
    {
        $course = $this->findRaw($id);

        if (!$course) {
            return ['ok' => false, 'errors' => ['Curso nao encontrado.']];
        }

        if (!$this->canManage($course, $user)) {
            return ['ok' => false, 'errors' => ['Nao tem permissao para editar este curso.']];
        }

        $errors = $this->validate($data);

        if ($errors) {
            return ['ok' => false, 'errors' => $errors];
        }

        $isFree = ($data['pricing_type'] ?? 'paid') === 'free';
        $price = $isFree ? 0 : (float) str_replace(',', '.', (string) ($data['price'] ?? 0));
        $discountPrice = $this->discountPrice($data, $isFree, $price);
        $status = in_array($course['status'], ['published', 'suspended'], true) ? $course['status'] : 'draft';

        $updated = $this->updateCourse($id, [
            'category_id' => (int) $data['category_id'],
            'title' => trim($data['title']),
            'slug' => $this->slug((string) $data['title']),
            'subtitle' => trim($data['subtitle'] ?? ''),
            'description' => trim($data['description'] ?? ''),
            'promo_video_url' => trim($data['promo_video_url'] ?? ''),
            'cover_image_url' => trim($data['cover_image_url'] ?? ''),
            'cover_color' => $data['cover_color'] ?? '#0f766e',
            'level' => $data['level'] ?? 'all',
            'language' => trim($data['language'] ?? 'Portugues'),
            'price' => $price,
            'discount_price' => $discountPrice,
            'is_free' => $isFree,
            'is_featured' => !empty($data['is_featured']) && has_role('admin'),
            'access_type' => $data['access_type'] ?? 'lifetime',
            'access_duration_days' => (int) ($data['access_duration_days'] ?? 0),
            'certificate_enabled' => !empty($data['certificate_enabled']),
            'completion_percentage_required' => (int) ($data['completion_percentage_required'] ?? 100),
            'final_quiz_required' => !empty($data['final_quiz_required']),
            'final_quiz_pass_score' => max(1, (int) ($data['final_quiz_pass_score'] ?? 70)),
            'duration_minutes' => (int) ($data['duration_minutes'] ?? 0),
            'workload_hours' => (int) ($data['workload_hours'] ?? 0),
            'requirements' => trim($data['requirements'] ?? ''),
            'learning_outcomes' => trim($data['learning_outcomes'] ?? ''),
            'course_includes' => trim($data['course_includes'] ?? ''),
            'target_audience' => trim($data['target_audience'] ?? ''),
            'welcome_message' => trim($data['welcome_message'] ?? ''),
            'status' => $status,
            'updated_at' => date('c'),
        ]);

        $this->logs->log('course_updated', "Curso {$updated['title']} actualizado.", (int) $user['id']);

        return ['ok' => true, 'course' => $updated];
    }

    public function submit(int $id, array $user): array
    {
        $course = $this->findRaw($id);

        if (!$course) {
            return ['ok' => false, 'error' => 'Curso nao encontrado.'];
        }

        if (!$this->canManage($course, $user)) {
            return ['ok' => false, 'error' => 'Nao tem permissao para alterar este curso.'];
        }

        $checklist = $this->publicationChecklist($id);

        if (!$checklist['ready']) {
            return [
                'ok' => false,
                'error' => 'Curso incompleto para aprovacao. Complete: ' . implode(', ', $checklist['missing']) . '.',
                'checklist' => $checklist,
            ];
        }

        return $this->transition($id, $user, 'submitted', 'course_submitted', 'Curso submetido para aprovacao.');
    }

    public function publicationChecklist(int $courseId): array
    {
        $course = $this->findRaw($courseId);

        if (!$course) {
            return ['ready' => false, 'score' => 0, 'items' => [], 'missing' => ['curso']];
        }

        return $this->buildPublicationChecklist($course);
    }

    public function approve(int $id, int $adminId): array
    {
        $course = $this->findRaw($id);

        if (!$course) {
            return ['ok' => false, 'error' => 'Curso nao encontrado.'];
        }

        $updated = $this->updateCourse($id, [
            'status' => 'published',
            'approved_at' => date('c'),
            'approved_by' => $adminId,
            'published_at' => date('c'),
            'updated_at' => date('c'),
            'rejection_reason' => '',
        ]);

        $this->logs->log('course_approved', "Curso {$updated['title']} aprovado.", $adminId);

        return ['ok' => true, 'course' => $updated];
    }

    public function reject(int $id, int $adminId, string $reason = ''): array
    {
        $course = $this->findRaw($id);

        if (!$course) {
            return ['ok' => false, 'error' => 'Curso nao encontrado.'];
        }

        $updated = $this->updateCourse($id, [
            'status' => 'rejected',
            'rejection_reason' => trim($reason),
            'updated_at' => date('c'),
        ]);

        $this->logs->log('course_rejected', "Curso {$updated['title']} rejeitado.", $adminId);

        return ['ok' => true, 'course' => $updated];
    }

    public function suspend(int $id, int $adminId): array
    {
        $course = $this->findRaw($id);

        if (!$course) {
            return ['ok' => false, 'error' => 'Curso nao encontrado.'];
        }

        $updated = $this->updateCourse($id, [
            'status' => 'suspended',
            'updated_at' => date('c'),
        ]);

        $this->logs->log('course_suspended', "Curso {$updated['title']} suspenso.", $adminId);

        return ['ok' => true, 'course' => $updated];
    }

    public function canManage(array $course, array $user): bool
    {
        if (($user['role'] ?? '') === 'admin') {
            return true;
        }

        if (!in_array($user['role'] ?? '', ['instructor', 'institution'], true)) {
            return false;
        }

        return (int) ($course['owner_id'] ?? 0) === (int) ($user['id'] ?? 0);
    }

    public function updateReviewStats(int $courseId, float $rating, int $reviewsCount): void
    {
        $this->updateCourse($courseId, [
            'rating' => round($rating, 1),
            'reviews_count' => $reviewsCount,
            'updated_at' => date('c'),
        ]);
    }

    private function transition(int $id, array $user, string $status, string $action, string $message): array
    {
        $course = $this->findRaw($id);

        if (!$course) {
            return ['ok' => false, 'error' => 'Curso nao encontrado.'];
        }

        if (!$this->canManage($course, $user)) {
            return ['ok' => false, 'error' => 'Nao tem permissao para alterar este curso.'];
        }

        $updated = $this->updateCourse($id, [
            'status' => $status,
            'updated_at' => date('c'),
        ]);

        $this->logs->log($action, $message, (int) $user['id']);

        return ['ok' => true, 'course' => $updated];
    }

    private function validate(array $data): array
    {
        $errors = [];

        if (trim($data['title'] ?? '') === '') {
            $errors[] = 'O titulo e obrigatorio.';
        }

        if ((int) ($data['category_id'] ?? 0) <= 0) {
            $errors[] = 'Escolha uma categoria.';
        }

        if (trim($data['description'] ?? '') === '') {
            $errors[] = 'A descricao e obrigatoria.';
        }

        if (($data['pricing_type'] ?? 'paid') !== 'free') {
            $price = (float) str_replace(',', '.', (string) ($data['price'] ?? 0));
            $discountPrice = (float) str_replace(',', '.', (string) ($data['discount_price'] ?? 0));

            if ($price <= 0) {
                $errors[] = 'Cursos pagos precisam de preco maior que zero.';
            }

            if ($discountPrice > 0 && $discountPrice >= $price) {
                $errors[] = 'O preco promocional deve ser menor que o preco normal.';
            }
        }

        return $errors;
    }

    private function discountPrice(array $data, bool $isFree, float $price): float
    {
        if ($isFree) {
            return 0;
        }

        $discountPrice = (float) str_replace(',', '.', (string) ($data['discount_price'] ?? 0));

        return $discountPrice > 0 && $discountPrice < $price ? $discountPrice : 0;
    }

    private function filterAndHydrate(array $courses, array $filters = []): array
    {
        $category = (int) ($filters['category_id'] ?? 0);
        $status = $filters['status'] ?? '';
        $pricing = $filters['pricing'] ?? '';
        $search = strtolower(trim($filters['search'] ?? ''));

        $filtered = array_filter($courses, function (array $course) use ($category, $status, $pricing, $search): bool {
            if ($category > 0 && (int) ($course['category_id'] ?? 0) !== $category) {
                return false;
            }

            if ($status !== '' && ($course['status'] ?? '') !== $status) {
                return false;
            }

            if ($pricing === 'free' && empty($course['is_free'])) {
                return false;
            }

            if ($pricing === 'paid' && !empty($course['is_free'])) {
                return false;
            }

            if ($search !== '') {
                $haystack = strtolower(($course['title'] ?? '') . ' ' . ($course['subtitle'] ?? '') . ' ' . ($course['description'] ?? ''));

                if (!str_contains($haystack, $search)) {
                    return false;
                }
            }

            return true;
        });

        $hydrated = array_map(fn (array $course): array => $this->hydrate($course), $filtered);
        usort($hydrated, fn (array $a, array $b): int => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));

        return array_values($hydrated);
    }

    private function hydrate(array $course): array
    {
        $category = $this->categoryById((int) ($course['category_id'] ?? 0));
        $owner = $this->auth->findById((int) ($course['owner_id'] ?? 0));
        $checklist = $this->buildPublicationChecklist($course);

        $course['category_name'] = $category['name'] ?? 'Sem categoria';
        $course['owner_name'] = $owner['name'] ?? 'Plataforma';
        $course['publication_score'] = $checklist['score'];
        $course['publication_ready'] = $checklist['ready'];
        $course['publication_missing'] = $checklist['missing'];
        $course['cover_image_url'] = $course['cover_image_url'] ?? '';

        if (trim((string) $course['cover_image_url']) === '') {
            $course['cover_image_url'] = $this->fallbackCoverImage((int) ($course['category_id'] ?? 0), (string) ($course['title'] ?? ''));
        }

        unset($course['owner_password'], $owner['password']);

        return $course;
    }

    private function buildPublicationChecklist(array $course): array
    {
        $content = $this->contentSummary((int) ($course['id'] ?? 0));
        $isPaid = empty($course['is_free']);
        $items = [
            ['key' => 'titulo', 'label' => 'Titulo claro', 'passed' => strlen(trim((string) ($course['title'] ?? ''))) >= 8, 'hint' => 'Use um titulo especifico e vendavel.'],
            ['key' => 'subtitulo', 'label' => 'Subtitulo/promessa', 'passed' => strlen(trim((string) ($course['subtitle'] ?? ''))) >= 20, 'hint' => 'Explique rapidamente o resultado do curso.'],
            ['key' => 'descricao', 'label' => 'Descricao completa', 'passed' => strlen(trim((string) ($course['description'] ?? ''))) >= 120, 'hint' => 'Descreva problema, metodo e resultado esperado.'],
            ['key' => 'capa', 'label' => 'Capa propria', 'passed' => trim((string) ($course['cover_image_url'] ?? '')) !== '', 'hint' => 'Adicione uma imagem de capa do curso.'],
            ['key' => 'video', 'label' => 'Video de apresentacao', 'passed' => trim((string) ($course['promo_video_url'] ?? '')) !== '', 'hint' => 'Inclua um video curto explicando o que o aluno vai aprender.'],
            ['key' => 'resultados', 'label' => 'Minimo 3 resultados', 'passed' => $this->lineCount((string) ($course['learning_outcomes'] ?? '')) >= 3, 'hint' => 'Liste pelo menos 3 itens em "O que o aluno vai aprender".'],
            ['key' => 'publico', 'label' => 'Publico-alvo definido', 'passed' => strlen(trim((string) ($course['target_audience'] ?? ''))) >= 20, 'hint' => 'Diga para quem o curso foi criado.'],
            ['key' => 'preco', 'label' => 'Preco valido', 'passed' => !$isPaid || (float) ($course['price'] ?? 0) > 0, 'hint' => 'Cursos pagos precisam de preco maior que zero.'],
            ['key' => 'modulo', 'label' => 'Pelo menos 1 modulo', 'passed' => $content['sections'] >= 1, 'hint' => 'Crie a estrutura do curso em modulos.'],
            ['key' => 'aula', 'label' => 'Pelo menos 1 aula', 'passed' => $content['lessons'] >= 1, 'hint' => 'Adicione aulas gravadas, texto ou PDF.'],
            ['key' => 'preview', 'label' => 'Aula gratuita de preview', 'passed' => $content['previews'] >= 1, 'hint' => 'Marque uma aula como pre-visualizacao gratuita.'],
        ];

        $passed = count(array_filter($items, fn (array $item): bool => $item['passed']));
        $total = count($items);
        $missing = array_values(array_map(
            fn (array $item): string => $item['label'],
            array_filter($items, fn (array $item): bool => !$item['passed'])
        ));

        return [
            'ready' => $passed === $total,
            'score' => (int) round(($passed / max(1, $total)) * 100),
            'items' => $items,
            'missing' => $missing,
        ];
    }

    private function contentSummary(int $courseId): array
    {
        $sections = array_values(array_filter(
            $this->sections->all(),
            fn (array $section): bool => (int) ($section['course_id'] ?? 0) === $courseId
        ));
        $lessons = array_values(array_filter(
            $this->lessons->all(),
            fn (array $lesson): bool => (int) ($lesson['course_id'] ?? 0) === $courseId
        ));

        return [
            'sections' => count($sections),
            'lessons' => count($lessons),
            'previews' => count(array_filter($lessons, fn (array $lesson): bool => !empty($lesson['is_preview']))),
        ];
    }

    private function lineCount(string $value): int
    {
        $parts = preg_split('/[\r\n;]+/', $value) ?: [];
        $parts = array_filter(array_map('trim', $parts), fn (string $line): bool => $line !== '');

        return count($parts);
    }

    private function fallbackCoverImage(int $categoryId, string $title): string
    {
        $images = [
            1 => 'https://images.unsplash.com/photo-1515879218367-8466d910aaa4?auto=format&fit=crop&w=900&q=80',
            2 => 'https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=900&q=80',
            3 => 'https://images.unsplash.com/photo-1561070791-2526d30994b5?auto=format&fit=crop&w=900&q=80',
            4 => 'https://images.unsplash.com/photo-1456513080510-7bf3a84b82f8?auto=format&fit=crop&w=900&q=80',
        ];

        if (str_contains(strtolower($title), 'excel')) {
            return 'https://images.unsplash.com/photo-1554224155-6726b3ff858f?auto=format&fit=crop&w=900&q=80';
        }

        return $images[$categoryId] ?? 'https://images.unsplash.com/photo-1498050108023-c5249f4df085?auto=format&fit=crop&w=900&q=80';
    }

    private function categoryById(int $id): ?array
    {
        foreach ($this->categories->all() as $category) {
            if ((int) ($category['id'] ?? 0) === $id) {
                return $category;
            }
        }

        return null;
    }

    private function findRaw(int $id): ?array
    {
        foreach ($this->courses->all() as $course) {
            if ((int) ($course['id'] ?? 0) === $id) {
                return $course;
            }
        }

        return null;
    }

    private function updateCourse(int $id, array $changes): array
    {
        $records = $this->courses->all();
        $updated = [];

        foreach ($records as $index => $course) {
            if ((int) ($course['id'] ?? 0) === $id) {
                $records[$index] = array_merge($course, $changes);
                $updated = $records[$index];
                break;
            }
        }

        $this->courses->save($records);

        return $updated;
    }

    private function ownerType(array $user): string
    {
        return match ($user['role'] ?? '') {
            'institution' => 'institution',
            'admin' => 'platform',
            default => 'instructor',
        };
    }

    private function slug(string $value): string
    {
        $slug = strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $value) ?: '', '-'));

        return $slug ?: 'curso';
    }

    private function seedCategories(): void
    {
        if ($this->categories->all()) {
            return;
        }

        $now = date('c');

        $this->categories->save([
            ['id' => 1, 'name' => 'Tecnologia', 'slug' => 'tecnologia', 'description' => 'Programacao, dados e ferramentas digitais.', 'status' => 'active', 'created_at' => $now, 'updated_at' => $now],
            ['id' => 2, 'name' => 'Negocios', 'slug' => 'negocios', 'description' => 'Empreendedorismo, vendas e gestao.', 'status' => 'active', 'created_at' => $now, 'updated_at' => $now],
            ['id' => 3, 'name' => 'Design', 'slug' => 'design', 'description' => 'Design grafico, produto e criatividade.', 'status' => 'active', 'created_at' => $now, 'updated_at' => $now],
            ['id' => 4, 'name' => 'Idiomas', 'slug' => 'idiomas', 'description' => 'Linguas para estudo e trabalho.', 'status' => 'active', 'created_at' => $now, 'updated_at' => $now],
        ]);
    }

    private function seedCourses(): void
    {
        if ($this->courses->all()) {
            return;
        }

        $admin = $this->auth->findByEmail('admin@mozcursos.local');
        $ownerId = (int) ($admin['id'] ?? 1);
        $now = date('c');

        $this->courses->save([
            [
                'id' => 1,
                'owner_type' => 'platform',
                'owner_id' => $ownerId,
                'category_id' => 1,
                'title' => 'Excel Profissional para Negocios',
                'slug' => 'excel-profissional-para-negocios',
                'subtitle' => 'Aprenda folhas de calculo para vendas, caixa e relatorios.',
                'description' => 'Curso pratico para quem quer organizar dados, controlar vendas e criar relatorios profissionais em Excel.',
                'cover_color' => '#0f766e',
                'level' => 'beginner',
                'language' => 'Portugues',
                'price' => 1500,
                'currency' => 'MZN',
                'is_free' => false,
                'is_featured' => true,
                'access_type' => 'lifetime',
                'access_duration_days' => 0,
                'certificate_enabled' => true,
                'completion_percentage_required' => 100,
                'duration_minutes' => 240,
                'workload_hours' => 8,
                'requirements' => 'Computador ou telemovel com acesso ao Excel ou Google Sheets.',
                'learning_outcomes' => 'Criar tabelas; usar formulas; montar relatorios; analisar vendas.',
                'target_audience' => 'Empreendedores, assistentes administrativos e estudantes.',
                'status' => 'published',
                'rejection_reason' => '',
                'rating' => 4.8,
                'reviews_count' => 24,
                'students_count' => 186,
                'published_at' => $now,
                'approved_at' => $now,
                'approved_by' => $ownerId,
                'created_at' => $now,
                'updated_at' => $now,
            ],
            [
                'id' => 2,
                'owner_type' => 'platform',
                'owner_id' => $ownerId,
                'category_id' => 2,
                'title' => 'Como Vender Online em Mocambique',
                'slug' => 'como-vender-online-em-mocambique',
                'subtitle' => 'Da oferta ao pagamento manual com clientes locais.',
                'description' => 'Aprenda a estruturar uma oferta simples, divulgar, fechar vendas e acompanhar pagamentos no contexto local.',
                'cover_color' => '#b45309',
                'level' => 'all',
                'language' => 'Portugues',
                'price' => 0,
                'currency' => 'MZN',
                'is_free' => true,
                'is_featured' => true,
                'access_type' => 'lifetime',
                'access_duration_days' => 0,
                'certificate_enabled' => false,
                'completion_percentage_required' => 100,
                'duration_minutes' => 95,
                'workload_hours' => 3,
                'requirements' => 'Vontade de vender e acesso a internet.',
                'learning_outcomes' => 'Definir oferta; comunicar valor; organizar pagamentos; acompanhar clientes.',
                'target_audience' => 'Pequenos negocios, freelancers e criadores.',
                'status' => 'published',
                'rejection_reason' => '',
                'rating' => 4.6,
                'reviews_count' => 18,
                'students_count' => 342,
                'published_at' => $now,
                'approved_at' => $now,
                'approved_by' => $ownerId,
                'created_at' => $now,
                'updated_at' => $now,
            ],
        ]);
    }
}
