<?php

declare(strict_types=1);

namespace App\Http\Requests\Academy;

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

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

    protected function prepareForValidation(): void
    {
        $this->merge([
            'featured' => $this->boolean('featured'),
            'prompt_of_week' => $this->boolean('prompt_of_week'),
            'active' => $this->boolean('active', true),
            'tags' => array_values(array_filter((array) $this->input('tags', []))),
            'tool_notes' => (array) $this->input('tool_notes', []),
        ]);
    }

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

        return [
            'category_id' => ['nullable', 'integer', 'exists:academy_categories,id'],
            'title' => ['required', 'string', 'max:180'],
            'slug' => ['required', 'string', 'max:180', Rule::unique('academy_prompt_templates', 'slug')->ignore($promptId)],
            'excerpt' => ['nullable', 'string'],
            'prompt' => ['required', 'string'],
            'negative_prompt' => ['nullable', 'string'],
            'usage_notes' => ['nullable', 'string'],
            'workflow_notes' => ['nullable', 'string'],
            'difficulty' => ['required', 'string', Rule::in((array) config('academy.difficulty_levels', []))],
            'access_level' => ['required', 'string', Rule::in(['free', 'creator', 'pro'])],
            'aspect_ratio' => ['nullable', 'string', 'max:20'],
            'tags' => ['nullable', 'array'],
            'tags.*' => ['string', 'max:60'],
            'tool_notes' => ['nullable', 'array'],
            'preview_image' => ['nullable', 'string', 'max:2048'],
            'featured' => ['required', 'boolean'],
            'prompt_of_week' => ['required', 'boolean'],
            'active' => ['required', 'boolean'],
            'published_at' => ['nullable', 'date'],
            'seo_title' => ['nullable', 'string', 'max:180'],
            'seo_description' => ['nullable', 'string', 'max:255'],
        ];
    }
}