<?php

declare(strict_types=1);

namespace App\Http\Requests\Academy;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpsertAcademyLessonRequest extends FormRequest
{
    public function authorize(): bool
    {
        return (bool) $this->user()?->hasStaffAccess();
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'reading_minutes' => $this->filled('reading_minutes') ? (int) $this->input('reading_minutes') : 5,
            'featured' => $this->boolean('featured'),
            'active' => $this->boolean('active', true),
        ]);
    }

    public function rules(): array
    {
        $lessonId = $this->route('academyLesson')?->id;

        return [
            'category_id' => ['nullable', 'integer', 'exists:academy_categories,id'],
            'title' => ['required', 'string', 'max:180'],
            'slug' => ['required', 'string', 'max:180', Rule::unique('academy_lessons', 'slug')->ignore($lessonId)],
            'excerpt' => ['nullable', 'string'],
            'content' => ['nullable', 'string'],
            'difficulty' => ['required', 'string', Rule::in((array) config('academy.difficulty_levels', []))],
            'access_level' => ['required', 'string', Rule::in(['free', 'creator', 'pro'])],
            'lesson_type' => ['required', 'string', 'max:80'],
            'cover_image' => ['nullable', 'string', 'max:2048'],
            'video_url' => ['nullable', 'string', 'max:2048'],
            'reading_minutes' => ['required', 'integer', 'min:1', 'max:999'],
            'featured' => ['required', 'boolean'],
            'active' => ['required', 'boolean'],
            'published_at' => ['nullable', 'date'],
            'seo_title' => ['nullable', 'string', 'max:180'],
            'seo_description' => ['nullable', 'string', 'max:255'],
        ];
    }
}