<?php

namespace App\Http\Requests\Messenger;

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

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

    public function rules(): array
    {
        return [
            'content' => ['required_without:attachments', 'nullable', 'string', 'max:4000'],
            'type' => ['nullable', 'string', Rule::in(['text', 'image', 'video', 'audio', 'file'])],
            'client_generated_id' => ['required', 'string', 'max:64'],
            'reply_to_message_id' => ['nullable', 'integer', 'exists:messages,id'],
            'attachments' => ['nullable', 'array', 'max:10'],
            'attachments.*' => ['file', 'max:50240'], // 50MB max per file
            'metadata' => ['nullable', 'array'],
        ];
    }

    public function messages(): array
    {
        return [
            'content.required_without' => 'Message content is required when no attachments are provided.',
            'content.max' => 'Message content cannot exceed 4000 characters.',
            'client_generated_id.required' => 'Client generated ID is required for message deduplication.',
            'attachments.max' => 'Maximum 10 attachments allowed per message.',
            'attachments.*.max' => 'Each attachment cannot exceed 50MB.',
            'reply_to_message_id.exists' => 'Reply target message does not exist.',
        ];
    }

    protected function prepareForValidation(): void
    {
        // Set default type based on content
        if (!$this->has('type')) {
            $type = 'text';
            if ($this->hasFile('attachments')) {
                $firstFile = $this->file('attachments')[0] ?? null;
                if ($firstFile) {
                    $mimeType = $firstFile->getMimeType();
                    if (str_starts_with($mimeType, 'image/')) {
                        $type = 'image';
                    } elseif (str_starts_with($mimeType, 'video/')) {
                        $type = 'video';
                    } elseif (str_starts_with($mimeType, 'audio/')) {
                        $type = 'audio';
                    } else {
                        $type = 'file';
                    }
                }
            }
            $this->merge(['type' => $type]);
        }

        // Generate client_generated_id if not provided
        if (!$this->has('client_generated_id')) {
            $this->merge([
                'client_generated_id' => uniqid($this->user()->id . '_', true)
            ]);
        }
    }
}
