<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ShopMediaController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'image' => ['required', 'image', 'mimes:jpg,jpeg,png,webp,gif', 'max:10240'],
        ]);
        $path = $validated['image']->store('shop/'.now()->format('Y/m'), 'public');

        return response()->json([
            'message' => 'Image uploaded.',
            // Keep the URL host-independent. The frontend resolves this path
            // against the configured API origin in local and production setups.
            'data' => ['path' => $path, 'url' => '/storage/'.$path],
        ], 201);
    }

    public function destroy(Request $request): JsonResponse
    {
        $validated = $request->validate(['path' => ['required', 'string', 'max:1000']]);
        $path = ltrim($validated['path'], '/');

        abort_unless(str_starts_with($path, 'shop/'), 422, 'Only Shop media can be deleted here.');
        Storage::disk('public')->delete($path);

        return response()->json(['message' => 'Image deleted.']);
    }
}
