<?php

namespace App\Http\Controllers;

use App\Http\Requests\VideoRequest;
use App\Models\Video;
use Inertia\Inertia;
use Inertia\Response;

/**
 * Controlador VideoController
 *
 * Maneja la gestión de videos usando Inertia.js.
 */
class VideoController extends Controller
{
    /**
     * Muestra la lista de videos.
     *
     * @return Response
     */
    public function index()
    {
        $perPage = request('per_page', 10);
        $search = request('search', '');

        $videos = Video::latest()
            ->where('key', 'like', "%{$search}%")
            ->paginate($perPage)
            ->appends(['search' => $search, 'per_page' => $perPage]);

        return Inertia::render('Videos/Index', [
            'videos' => $videos,
            'filters' => request()->only(['search', 'per_page']),
            'status' => session()->only(['success', 'error']),
        ]);
    }

    /**
     * Almacena un nuevo video en la base de datos.
     *
     * @param VideoRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(VideoRequest $request)
    {
        $video = Video::create($request->validated());
        return redirect()->back()->with('success', 'Video: ' . $video->key . ' creado exitosamente.');
    }

    /**
     * Actualiza un video existente en la base de datos.
     *
     * @param VideoRequest $request
     * @param Video $video
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(VideoRequest $request, Video $video)
    {
        $video->update($request->validated());

        return redirect()->back()->with('success', 'Video: ' . $video->key . ' actualizado exitosamente.');
    }

    /**
     * Elimina un video de la base de datos.
     *
     * @param Video $video
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Video $video)
    {
        $video->delete();

        return redirect()->back()->with('success', 'Video eliminado exitosamente.');
    }
}
