<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreReviewRequest;
use App\Http\Resources\ReviewResource;
use App\Models\Review;
use App\Models\User;
use App\Services\FcmService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ReviewController extends Controller
{
    public function store(StoreReviewRequest $request): JsonResponse
    {
        $exists = Review::where('post_id', $request->post_id)
            ->where('reviewer_id', $request->user()->id)
            ->exists();

        if ($exists) {
            return response()->json([
                'success' => false,
                'message' => 'Kamu sudah memberikan review untuk transaksi ini',
            ], 422);
        }

        $review = Review::create([
            'post_id' => $request->post_id,
            'reviewer_id' => $request->user()->id,
            'reviewee_id' => $request->reviewee_id,
            'rating' => $request->rating,
            'comment' => $request->comment,
        ]);

        $review->load('reviewer', 'reviewee');

        // Notify reviewee
        $reviewee = User::find($request->reviewee_id);
        $stars = str_repeat('⭐', $request->rating);
        app(FcmService::class)->sendToUser(
            $reviewee,
            'Kamu mendapat review baru!',
            "{$review->reviewer->name} memberimu $stars",
            ['type' => 'review', 'reviewer_id' => (string) $request->user()->id],
        );

        return response()->json([
            'success' => true,
            'data' => new ReviewResource($review),
            'message' => 'Review berhasil dikirim',
        ], 201);
    }

    public function userReviews(string $username): JsonResponse
    {
        $user = User::where('username', $username)->firstOrFail();

        $reviews = Review::with('reviewer')
            ->where('reviewee_id', $user->id)
            ->latest()
            ->paginate(15);

        return response()->json([
            'success' => true,
            'data' => ReviewResource::collection($reviews),
            'meta' => [
                'current_page' => $reviews->currentPage(),
                'last_page' => $reviews->lastPage(),
                'total' => $reviews->total(),
                'average_rating' => $reviews->avg('rating'),
            ],
        ]);
    }
}
