<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\UpdateMediaRequest;
use App\Http\Requests\Admin\UploadMediaRequest;
use App\Models\Media;
use App\Services\ActivityLogger;
use App\Services\MediaService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\View;

class MediaController extends Controller
{
    public function index(): View
    {
        Gate::authorize('viewAny', Media::class);

        $query = Media::query()->with('usages')->ordered();
        if ($folder = request('folder')) {
            $query->where('folder', $folder);
        }
        if ($search = request('q')) {
            $query->where(fn ($q) => $q->where('filename', 'like', "%{$search}%")->orWhere('title', 'like', "%{$search}%"));
        }

        return view('admin.media.index', ['media' => $query->get()]);
    }

    public function store(UploadMediaRequest $request, MediaService $mediaService, ActivityLogger $logger): RedirectResponse
    {
        Gate::authorize('create', Media::class);

        $media = $mediaService->store($request->file('file'), $request->input('folder', 'general'), auth()->id());
        $media->update($request->only(['title', 'alt_text', 'caption']));
        $logger->log('media.uploaded', $media, "Média téléversé: {$media->filename}");

        return back()->with('status', 'Média téléversé.');
    }

    public function update(UpdateMediaRequest $request, Media $media, ActivityLogger $logger): RedirectResponse
    {
        Gate::authorize('update', $media);

        $media->update($request->validated());
        $logger->log('media.updated', $media, "Média modifié: {$media->filename}");

        return back()->with('status', 'Média enregistré.');
    }

    public function destroy(Media $media, MediaService $mediaService, ActivityLogger $logger): RedirectResponse
    {
        Gate::authorize('delete', $media);

        if (! $mediaService->canDelete($media)) {
            return back()->withErrors(['media' => 'Ce média est protégé ou utilisé et ne peut pas être supprimé.']);
        }

        $media->delete();
        $logger->log('media.deleted', $media, "Média archivé: {$media->filename}");

        return back()->with('status', 'Média archivé.');
    }

    public function forceDestroy(Media $media, MediaService $mediaService, ActivityLogger $logger): RedirectResponse
    {
        Gate::authorize('forceDelete', $media);

        if (! $mediaService->canDelete($media, true)) {
            return back()->withErrors(['media' => 'Ce média est protégé ou encore utilisé.']);
        }

        $filename = $media->filename;
        $media->forceDelete();
        $logger->log('media.force_deleted', $media, "Média supprimé définitivement: {$filename}");

        return back()->with('status', 'Média supprimé définitivement.');
    }
}
