<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Marketplace;

use App\Http\Controllers\Controller;
use App\Models\MarketplaceItem;
use App\Services\Marketplace\MarketplaceReviewService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MarketplaceReviewController extends Controller
{
    public function __construct(private readonly MarketplaceReviewService $service) {}

    public function store(Request $request, string $id): JsonResponse
    {
        $user = $request->user();
        if (! $user) abort(401);

        $item = MarketplaceItem::findOrFail($id);
        $data = $request->validate([
            'rating' => ['required', 'integer', 'min:1', 'max:5'],
            'review' => ['nullable', 'string', 'max:2000'],
        ]);

        $r = $this->service->upsert($item, $user->id, (int) $data['rating'], $data['review'] ?? null);
        return response()->json(['data' => $r], 201);
    }
}
