<?php

namespace App\Http\Requests\Messenger;

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

class ParticipantUpdateRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true; // Authorization handled in controller
    }

    public function rules(): array
    {
        return [
            'action' => ['required', 'string', Rule::in(['add', 'remove', 'update_role', 'mute', 'unmute'])],
            'user_ids' => ['required_if:action,add,remove', 'array', 'max:50'],
            'user_ids.*' => ['integer', 'exists:users,id'],
            'user_id' => ['required_if:action,update_role,mute,unmute', 'integer', 'exists:users,id'],
            'role' => ['required_if:action,update_role', 'string', Rule::in(['member', 'admin'])],
            'mute_duration' => ['nullable', 'integer', 'min:1', 'max:43200'], // Max 30 days in minutes
        ];
    }

    public function messages(): array
    {
        return [
            'action.required' => 'Action is required.',
            'action.in' => 'Invalid action specified.',
            'user_ids.required_if' => 'User IDs are required for this action.',
            'user_id.required_if' => 'User ID is required for this action.',
            'role.required_if' => 'Role is required when updating user role.',
            'role.in' => 'Invalid role specified.',
            'mute_duration.max' => 'Mute duration cannot exceed 30 days.',
        ];
    }

    protected function prepareForValidation(): void
    {
        // Remove current user from user_ids if present
        if ($this->has('user_ids') && is_array($this->user_ids)) {
            $this->merge([
                'user_ids' => array_filter(
                    array_map('intval', $this->user_ids),
                    fn($id) => $id !== $this->user()->id
                )
            ]);
        }

        // Ensure user_id is not current user for role updates
        if ($this->action === 'update_role' && $this->user_id === $this->user()->id) {
            $this->merge(['user_id' => null]);
        }
    }
}
