<?php

namespace App\Http\Requests\Messenger;

use Illuminate\Foundation\Http\FormRequest;

class AttachmentStoreRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'file' => ['required', 'file', 'max:50240'], // 50MB max
            'type' => ['nullable', 'string', 'in:image,video,audio,document'],
        ];
    }

    public function messages(): array
    {
        return [
            'file.required' => 'File is required.',
            'file.max' => 'File size cannot exceed 50MB.',
        ];
    }

    protected function prepareForValidation(): void
    {
        // Auto-detect type from file if not provided
        if (!$this->has('type') && $this->hasFile('file')) {
            $file = $this->file('file');
            $mimeType = $file->getMimeType();
            
            $type = 'document'; // default
            if (str_starts_with($mimeType, 'image/')) {
                $type = 'image';
            } elseif (str_starts_with($mimeType, 'video/')) {
                $type = 'video';
            } elseif (str_starts_with($mimeType, 'audio/')) {
                $type = 'audio';
            }
            
            $this->merge(['type' => $type]);
        }
    }
}
