<?php

declare(strict_types=1);

namespace App\Http\Requests\Academy;

use App\Models\AcademyChallenge;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

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

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

        return [
            'title' => ['required', 'string', 'max:180'],
            'slug' => ['required', 'string', 'max:180', Rule::unique('academy_challenges', 'slug')->ignore($challengeId)],
            'excerpt' => ['nullable', 'string'],
            'description' => ['nullable', 'string'],
            'brief' => ['nullable', 'string'],
            'rules' => ['nullable', 'string'],
            'access_level' => ['required', 'string', Rule::in(['free', 'creator', 'pro'])],
            'status' => ['required', 'string', Rule::in([
                AcademyChallenge::STATUS_DRAFT,
                AcademyChallenge::STATUS_SCHEDULED,
                AcademyChallenge::STATUS_ACTIVE,
                AcademyChallenge::STATUS_VOTING,
                AcademyChallenge::STATUS_COMPLETED,
                AcademyChallenge::STATUS_ARCHIVED,
            ])],
            'starts_at' => ['nullable', 'date'],
            'ends_at' => ['nullable', 'date'],
            'voting_starts_at' => ['nullable', 'date'],
            'voting_ends_at' => ['nullable', 'date'],
            'cover_image' => ['nullable', 'string', 'max:2048'],
            'prize_text' => ['nullable', 'string', 'max:180'],
            'required_tags' => ['nullable', 'array'],
            'required_tags.*' => ['string', 'max:60'],
            'allowed_categories' => ['nullable', 'array'],
            'allowed_categories.*' => ['string', 'max:80'],
            'featured' => ['required', 'boolean'],
            'active' => ['required', 'boolean'],
        ];
    }
}