<?php

namespace App\Http\Requests\Messenger;

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

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

    public function rules(): array
    {
        return [
            'type' => ['required', 'string', Rule::in(['dm', 'group'])],
            'title' => ['required_if:type,group', 'nullable', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:1000'],
            'participant_ids' => ['required', 'array', 'min:1', 'max:100'],
            'participant_ids.*' => ['integer', 'exists:users,id'],
            'avatar' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,webp', 'max:2048'],
            'settings' => ['nullable', 'array'],
            'settings.join_approval_required' => ['nullable', 'boolean'],
            'settings.message_retention_days' => ['nullable', 'integer', 'min:1', 'max:365'],
        ];
    }

    public function messages(): array
    {
        return [
            'type.required' => 'Conversation type is required.',
            'type.in' => 'Conversation type must be either dm or group.',
            'title.required_if' => 'Group conversations must have a title.',
            'participant_ids.required' => 'At least one participant is required.',
            'participant_ids.min' => 'At least one participant is required.',
            'participant_ids.max' => 'Maximum 100 participants allowed.',
            'participant_ids.*.exists' => 'One or more participants do not exist.',
        ];
    }

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

        // For DM, ensure exactly one participant
        if ($this->type === 'dm' && count($this->participant_ids ?? []) !== 1) {
            $this->merge(['participant_ids' => array_slice($this->participant_ids ?? [], 0, 1)]);
        }
    }
}
