<?php

namespace App\Http\Requests;

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

/**
 * StoreDigitalMachineRequest
 *
 * Validates digital health machine creation data.
 * Health Marketors can add machines for marketing.
 *
 * Requirements: 3.1, 10.1
 */
class StoreDigitalMachineRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        // Must be authenticated with Health Marketor role or admin
        return auth()->check() && auth()->user()->can('create machines');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            // Basic Information
            'name' => [
                'required',
                'string',
                'max:191',
                'min:3',
            ],
            'short_name' => [
                'nullable',
                'string',
                'max:100',
            ],
            'brand' => [
                'nullable',
                'string',
                'max:100',
            ],
            'model' => [
                'nullable',
                'string',
                'max:100',
            ],
            'category' => [
                'required',
                'string',
                'max:100',
            ],
            'vendor' => [
                'nullable',
                'string',
                'max:191',
            ],
            'manufacturers' => [
                'nullable',
                'string',
                'max:191',
            ],

            // Media
            'images' => [
                $this->isMethod('PUT') || $this->isMethod('PATCH') ? 'nullable' : 'required',
                'array',
                'min:1',
                'max:15',
            ],
            'images.*' => [
                'image',
                'mimes:jpeg,jpg,png,webp',
                'max:5120', // 5MB max for machines
            ],
            'primary_image' => [
                'nullable',
                'integer',
                'min:0',
            ],
            'video_clips' => [
                'nullable',
                'array',
                'max:5',
            ],
            'video_clips.*' => [
                'file',
                'mimes:mp4,webm,mov,avi',
                'max:51200', // 50MB max for videos
            ],

            // Content
            'description' => [
                'required',
                'string',
                'min:50',
                'max:10000',
            ],
            'specifications' => [
                'nullable',
                'array',
            ],
            'specifications.*.key' => [
                'required',
                'string',
                'max:191',
            ],
            'specifications.*.value' => [
                'required',
                'string',
                'max:500',
            ],
            'functionalities' => [
                'nullable',
                'array',
            ],
            'functionalities.*' => [
                'string',
                'max:500',
            ],
            'website_links' => [
                'nullable',
                'array',
                'max:10',
            ],
            'website_links.*' => [
                'url',
                'max:191',
            ],

            // Contact Information — accept both flat fields (from create form) and nested array (from edit form)
            'contact_info' => [
                'nullable',
                'array',
            ],
            'contact_info.phone' => [
                'nullable',
                'string',
                'max:50',
            ],
            'contact_info.email' => [
                'nullable',
                'email',
                'max:191',
            ],
            'contact_info.website' => [
                'nullable',
                'url',
                'max:191',
            ],
            'contact_info.address' => [
                'nullable',
                'string',
                'max:500',
            ],
            // Flat contact fields used by the create form
            'contact_phone' => [
                'nullable',
                'string',
                'max:50',
            ],
            'contact_email' => [
                'nullable',
                'email',
                'max:191',
            ],

            // Pricing
            'price_ssp' => [
                'nullable',
                'numeric',
                'min:0',
                'max:9999999999.99',
            ],
            'price_usd' => [
                'nullable',
                'numeric',
                'min:0',
                'max:9999999999.99',
            ],
            'price_publishable' => [
                'boolean',
            ],
            'price_note' => [
                'nullable',
                'string',
                'max:191',
            ],
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'name.required' => 'The machine name is required.',
            'name.min' => 'The machine name must be at least 3 characters.',
            'category.required' => 'Please select a category.',
            'description.required' => 'A description is required.',
            'description.min' => 'Please provide a more detailed description (at least 50 characters).',
            'images.required' => 'At least one image is required.',
            'images.min' => 'At least one image is required.',
            'images.max' => 'You can upload a maximum of 15 images.',
            'images.*.max' => 'Each image must not exceed 5MB.',
            'video_clips.max' => 'You can upload a maximum of 5 videos.',
            'video_clips.*.max' => 'Each video must not exceed 50MB.',
            'functionalities.*.max' => 'Each functionality description must not exceed 500 characters.',
            'price_ssp.min' => 'Price must be a positive number.',
            'price_usd.min' => 'Price must be a positive number.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Sanitize text inputs
        $this->merge([
            'name' => strip_tags($this->name),
            'brand' => $this->brand ? strip_tags($this->brand) : null,
            'model' => $this->model ? strip_tags($this->model) : null,
            'category' => strip_tags($this->category),
            'vendor' => $this->vendor ? strip_tags($this->vendor) : null,
            'manufacturers' => $this->manufacturers ? strip_tags($this->manufacturers) : null,
            'description' => strip_tags($this->description, '<p><br><strong><em><ul><ol><li><table><td><th><tr>'),
            'price_note' => $this->price_note ? strip_tags($this->price_note) : null,
        ]);

        // Set default for price_publishable
        if (!$this->has('price_publishable')) {
            $this->merge(['price_publishable' => true]);
        }
    }
}
