<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use App\Models\SocialPost;

class StoreReelRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'source_posts' => 'required|array|min:1',
            'source_posts.*' => 'exists:social_posts,id',
            'template' => 'required|string|in:' . implode(',', array_keys(config('reels.templates', []))),
            'options' => 'nullable|array',
            'options.aspect_ratio' => 'nullable|string|in:9:16,1:1,4:5',
            'options.music' => 'nullable|string|max:255',
            'options.overlay' => 'nullable|string|max:255',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            // Verify that all selected posts belong to the current user (for creators)
            // or to creators of the current brand (for brand admins)
            if ($this->has('source_posts')) {
                $posts = SocialPost::whereIn('id', $this->source_posts)->get();
                
                foreach ($posts as $post) {
                    if (Auth::user()->hasRole('creator')) {
                        // Creator can only use their own posts
                        if ($post->user_id != Auth::id()) {
                            $validator->errors()->add('source_posts', 'You can only use your own social posts.');
                            break;
                        }
                    } elseif (Auth::user()->hasRole('brand_admin')) {
                        // Brand admin can only use posts from their brand's creators
                        if ($post->user->brand_id != Auth::user()->brand_id) {
                            $validator->errors()->add('source_posts', 'You can only use posts from your brand creators.');
                            break;
                        }
                    }
                }
            }
        });
    }
}