<?php

namespace App\Http\Controllers;

use App\Models\Media;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MediaController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $baseUrl = $request->getSchemeAndHttpHost();
        $media = Media::where('user_id', auth()->id())->get()->map(function ($item) use ($baseUrl) {
            $item->url = $baseUrl . '/' . $item->path;
            return $item;
        });
        return response()->json($media);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|file|max:10240', // 10MB max
            'name' => 'sometimes|string|max:255',
        ]);

        $file = $request->file('file');
        $originalName = $file->getClientOriginalName();
        $name = $request->input('name', pathinfo($originalName, PATHINFO_FILENAME));
        $extension = $file->getClientOriginalExtension();
        $size = $file->getSize();

        // Generate unique filename
        $filename = time() . '_' . uniqid() . '.' . $extension;

        // Store file
        $path = $file->storeAs('media', $filename, 'public');

        $media = Media::create([
            'user_id' => auth()->id(),
            'name' => $name,
            'path' => $path,
            'size' => $size,
        ]);

        $media->url = $request->getSchemeAndHttpHost() . '/' . $path;

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, string $id)
    {
        $media = Media::where('user_id', auth()->id())
            ->where('id', $id)
            ->firstOrFail();

        // Delete file from storage
        Storage::disk('public')->delete($media->path);

        $media->delete();

        return response()->json(['message' => 'Media deleted successfully']);
    }
}
