<?php

namespace App\Http\Controllers;

use App\Models\Media;
use App\Services\MediaUploadService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class MediaController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $media = Media::query()
            ->when($request->input('type'), fn ($q, $type) => $q->where('type', $type))
            ->when($request->input('search'), fn ($q, $s) => $q->where('original_name', 'like', "%{$s}%"))
            ->latest()
            ->paginate(24);

        return response()->json($media);
    }

    public function store(Request $request, MediaUploadService $uploads): JsonResponse
    {
        $request->validate([
            'file'       => 'required|file|mimes:jpg,jpeg,png,gif,webp,svg,mp4,webm,ogg,mov,pdf,doc,docx|max:102400',
            'collection' => 'nullable|string|max:100',
        ]);

        $media = $uploads->store($request->file('file'), $request->input('collection', 'library'));

        return response()->json($media);
    }

    public function destroy(Media $media, MediaUploadService $uploads): JsonResponse
    {
        abort_unless($media->user_id === auth()->id(), 403);

        $uploads->delete($media);

        return response()->json(['success' => true]);
    }

    public function serve(string $path): BinaryFileResponse
    {
        return $this->serveFromDisk('uploads', $path);
    }

    public function serveLegacy(string $path): BinaryFileResponse
    {
        return $this->serveFromDisk('public', $path);
    }

    private function serveFromDisk(string $disk, string $path): BinaryFileResponse
    {
        abort_unless(Storage::disk($disk)->exists($path), 404);

        return response()->file(Storage::disk($disk)->path($path));
    }
}
