<?php

/*
    Created by Mohamed.
*/


namespace App\Http\Controllers\API;

use App\Models\Review;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class ReviewController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum')->except(['index', 'show']);
    }

    public function index(Request $request)
    {
        $productId = $request->query('product_id');

        $query = Review::with(['user', 'product']);

        if ($productId) {
            $query->where('product_id', $productId);
        }

        $reviews = $query->paginate(10);

        if ($reviews->isEmpty() && $productId) {
            return response()->json(['message' => 'No reviews found for this product.'], 404);
        }

        return response()->json(['reviews' => $reviews], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'rating' => 'required|integer|between:1,5',
            'comment' => 'nullable|string|max:1000',
            'product_id' => 'required|exists:products,id',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $review = Review::create([
            'rating' => $request->rating,
            'comment' => $request->comment,
            'product_id' => $request->product_id,
            'user_id' => auth()->id(),
        ]);

        return response()->json(['review' => $review->load(['user', 'product'])], 201);
    }

    public function show(Review $review)
    {
        return response()->json(['review' => $review->load(['user', 'product'])], 200);
    }

    public function update(Request $request, Review $review)
    {
        $this->authorizeReview($review);

        $validator = Validator::make($request->all(), [
            'rating' => 'required|integer|between:1,5',
            'comment' => 'nullable|string|max:1000',
            'product_id' => 'required|exists:products,id',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $review->update([
            'rating' => $request->rating,
            'comment' => $request->comment,
            'product_id' => $request->product_id,
        ]);

        return response()->json(['review' => $review->load(['user', 'product'])], 200);
    }

    public function destroy(Review $review)
    {
        $this->authorizeReview($review);

        $review->delete();

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

    protected function authorizeReview(Review $review)
    {
        if ($review->user_id !== auth()->id()) {
            abort(403, 'Unauthorized action.');
        }
    }
}