<?php

namespace App\Http\Requests;

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

/**
 * StorePublishingPageRequest
 *
 * Validates dynamic publishing page creation data.
 * Only Manager and Super Manager can create pages.
 *
 * Requirements: 4.1, 4.2, 4.5, 10.1
 */
class StorePublishingPageRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth()->check() && auth()->user()->can('create pages');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            // Page Identity
            'title' => [
                'required',
                'string',
                'max:191',
                'min:3',
            ],
            'slug' => [
                'nullable',
                'string',
                'max:191',
                'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/',
                \Illuminate\Validation\Rule::unique('publishing_pages', 'slug')
                    ->ignore($this->route('page')),
            ],

            // Content Blocks
            'content_blocks' => [
                'nullable',
                'array',
            ],
            'content_blocks.*.type' => [
                'required',
                'string',
                Rule::in([
                    'hero', 'text', 'heading', 'image', 'image_grid',
                    'carousel', 'video', 'cta', 'split_screen',
                    'card_section', 'quote', 'accordion', 'tabs',
                    'divider', 'spacer',
                ]),
            ],

            // Hero Block
            'content_blocks.*.title' => [
                'required_if:content_blocks.*.type,hero,heading',
                'string',
                'max:191',
            ],
            'content_blocks.*.subtitle' => [
                'nullable',
                'string',
                'max:500',
            ],
            'content_blocks.*.background_image' => [
                'nullable',
                'string',
                'max:191',
            ],
            'content_blocks.*.background_color' => [
                'nullable',
                'string',
                'max:50',
            ],

            // Text/Paragraph Block
            'content_blocks.*.content' => [
                'required_if:content_blocks.*.type,text,quote',
                'string',
                'max:65000',
            ],

            // Image Block
            'content_blocks.*.image' => [
                'required_if:content_blocks.*.type,image',
                'string',
                'max:191',
            ],
            'content_blocks.*.alt_text' => [
                'nullable',
                'string',
                'max:191',
            ],
            'content_blocks.*.caption' => [
                'nullable',
                'string',
                'max:500',
            ],

            // Image Grid Block
            'content_blocks.*.images' => [
                'required_if:content_blocks.*.type,image_grid,carousel',
                'array',
            ],
            'content_blocks.*.columns' => [
                'nullable',
                'integer',
                'min:1',
                'max:6',
            ],

            // CTA Block
            'content_blocks.*.button_text' => [
                'required_if:content_blocks.*.type,cta',
                'string',
                'max:191',
            ],
            'content_blocks.*.button_url' => [
                'required_if:content_blocks.*.type,cta',
                'string',
                'max:191',
            ],
            'content_blocks.*.button_style' => [
                'nullable',
                'string',
                Rule::in(['primary', 'secondary', 'outline', 'ghost']),
            ],

            // Card Section Block
            'content_blocks.*.cards' => [
                'required_if:content_blocks.*.type,card_section',
                'array',
            ],
            'content_blocks.*.cards.*.title' => [
                'required',
                'string',
                'max:191',
            ],
            'content_blocks.*.cards.*.content' => [
                'required',
                'string',
                'max:1000',
            ],
            'content_blocks.*.cards.*.image' => [
                'nullable',
                'string',
                'max:191',
            ],
            'content_blocks.*.cards.*.link' => [
                'nullable',
                'string',
                'max:191',
            ],

            // Accordion Block
            'content_blocks.*.items' => [
                'required_if:content_blocks.*.type,accordion,tabs',
                'array',
            ],
            'content_blocks.*.items.*.title' => [
                'required',
                'string',
                'max:191',
            ],
            'content_blocks.*.items.*.content' => [
                'required',
                'string',
                'max:10000',
            ],

            // Theme Configuration
            'theme_colors' => [
                'nullable',
                'array',
            ],
            'theme_colors.primary' => [
                'nullable',
                'string',
                'regex:/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/',
            ],
            'theme_colors.secondary' => [
                'nullable',
                'string',
                'regex:/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/',
            ],
            'theme_colors.background' => [
                'nullable',
                'string',
                'max:50',
            ],

            // SEO Configuration
            'seo_meta' => [
                'nullable',
                'array',
            ],
            'seo_meta.meta_title' => [
                'nullable',
                'string',
                'max:191',
            ],
            'seo_meta.meta_description' => [
                'nullable',
                'string',
                'max:500',
            ],
            'seo_meta.keywords' => [
                'nullable',
                'array',
            ],
            'seo_meta.keywords.*' => [
                'string',
                'max:100',
            ],
            'seo_meta.og_image' => [
                'nullable',
                'string',
                'max:191',
            ],

            // Layout Settings
            'layout' => [
                'nullable',
                'string',
                Rule::in(['default', 'boxed', 'sidebar-left', 'sidebar-right']),
            ],
            'show_breadcrumbs' => [
                'boolean',
            ],
            'show_sidebar' => [
                'boolean',
            ],

            // Publication
            'is_published' => [
                'boolean',
            ],
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'title.required' => 'A page title is required.',
            'title.min' => 'The title must be at least 3 characters.',
            'slug.regex' => 'The slug must be lowercase letters, numbers, and hyphens only.',
            'slug.unique' => 'This slug is already in use.',
            'seo_meta.meta_description.max' => 'Meta description should be under 500 characters for SEO.',
            'theme_colors.primary.regex' => 'Primary color must be a valid hex color code (e.g., #10b981).',
            'theme_colors.secondary.regex' => 'Secondary color must be a valid hex color code.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Generate slug from title if not provided
        if (!$this->slug && $this->title) {
            $this->merge(['slug' => \Str::slug($this->title)]);
        }

        // Sanitize title
        if ($this->title) {
            $this->merge(['title' => strip_tags($this->title)]);
        }

        // Decode content_blocks_json into content_blocks array if provided
        if ($this->content_blocks_json) {
            $decoded = json_decode($this->content_blocks_json, true);
            if (is_array($decoded)) {
                $this->merge(['content_blocks' => $decoded]);
            }
        }

        // Set defaults
        $this->merge([
            'show_breadcrumbs' => $this->boolean('show_breadcrumbs', true),
            'show_sidebar' => $this->boolean('show_sidebar', false),
            'is_published' => $this->boolean('is_published', false),
        ]);
    }
}
