<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        return [
            'episode_name' => 'required|string|max:50',
            'order'        => 'required|max:255',
            'source_type'  => 'required|string|max:10',
            'runtime' => 'required|integer|min:1', // Runtime in minutes
            'file'         => 'nullable|file|mimes:mp4,mkv,webm,avi|max:102400',
            'file_url'     => 'nullable|string|max:255',
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $hasFile = $this->hasFile('file');
            $hasUrl  = $this->filled('file_url');
            $hasS3   = $this->filled('source_type');

            // ✅ Only check file/url rules if user provided something
            if ($hasFile || $hasUrl || $hasS3) {
                if (!$hasFile && !$hasUrl && !$hasS3) {
                    $validator->errors()->add('file', 'You must provide either a file or a file URL.');
                    $validator->errors()->add('file_url', 'You must provide either a file or a file URL.');
                }

                if ($hasFile && $hasUrl) {
                    $validator->errors()->add('file', 'Provide only one: a file OR a file URL — not both.');
                    $validator->errors()->add('file_url', 'Provide only one: a file OR a file URL — not both.');
                }

                // Optional: require source_type only when uploading file/url
                if (!$hasS3) {
                    $validator->errors()->add('source_type', 'Source type is required when uploading a file or file URL.');
                }
            }
        });
    }

    public function messages(): array
    {
        return [
            'file.mimes' => 'Allowed video formats are mp4, mkv, webm, and avi.',
            'file.max'   => 'Maximum file size is 100MB.',
        ];
    }
}
