<?php

declare(strict_types=1);

namespace App\Http\Requests\Academy;

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

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

    protected function prepareForValidation(): void
    {
        $this->merge([
            'one_time_price_cents' => $this->filled('one_time_price_cents') ? (int) $this->input('one_time_price_cents') : null,
            'featured' => $this->boolean('featured'),
            'active' => $this->boolean('active', true),
            'tags' => array_values(array_filter((array) $this->input('tags', []))),
            'prompt_ids' => array_values(array_filter(array_map('intval', (array) $this->input('prompt_ids', [])))),
        ]);
    }

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

        return [
            'title' => ['required', 'string', 'max:180'],
            'slug' => ['required', 'string', 'max:180', Rule::unique('academy_prompt_packs', 'slug')->ignore($packId)],
            'excerpt' => ['nullable', 'string'],
            'description' => ['nullable', 'string'],
            'access_level' => ['required', 'string', Rule::in(['free', 'creator', 'pro'])],
            'one_time_price_cents' => ['nullable', 'integer', 'min:0'],
            'currency' => ['required', 'string', 'size:3'],
            'cover_image' => ['nullable', 'string', 'max:2048'],
            'tags' => ['nullable', 'array'],
            'tags.*' => ['string', 'max:60'],
            'prompt_ids' => ['nullable', 'array'],
            'prompt_ids.*' => ['integer', 'exists:academy_prompt_templates,id'],
            'featured' => ['required', 'boolean'],
            'active' => ['required', 'boolean'],
            'published_at' => ['nullable', 'date'],
        ];
    }
}