<?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');

            if (!$hasFile && !$hasUrl) {
                $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.');
            }
        });
    }

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