<?php

namespace Modules\Media\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Media\Services\MediaService;

class MediaController extends Controller
{
    public function __construct(
        private MediaService $mediaService
    ) {}

    public function index(): JsonResponse
    {
        return response()->json($this->mediaService->getAll());
    }

    public function show(int $id): JsonResponse
    {
        $media = $this->mediaService->findById($id);
        if (!$media) {
            return response()->json(['message' => 'Media not found'], 404);
        }
        return response()->json($media);
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:jpg,jpeg,png,gif,webp,svg|max:2048',
            'type' => 'nullable|string|in:image,file,video',
            'mediable_type' => 'nullable|string',
            'mediable_id' => 'nullable|integer',
        ]);

        $file = $request->file('file');
        $type = $request->get('type', 'image');

        if ($request->filled('mediable_type') && $request->filled('mediable_id')) {
            $mediable = app($request->mediable_type)->find($request->mediable_id);
            if (!$mediable) {
                return response()->json(['message' => 'Mediable resource not found'], 404);
            }
            $media = $this->mediaService->upload($file, $type, $mediable);
        } else {
            $media = $this->mediaService->uploadWithoutMediable($file, $type);
        }

        return response()->json([
            'id' => $media->id,
            'url' => $this->mediaService->getUrl($media),
            'filename' => $media->filename,
            'mime_type' => $media->mime_type,
            'size' => $media->size,
        ], 201);
    }

    public function destroy(int $id): JsonResponse
    {
        $this->mediaService->delete($id);
        return response()->json(null, 204);
    }
}
