<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Review;
use App\Models\Trip;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReviewController extends Controller
{
    /**
     * POST /api/trips/{trip}/reviews
     * Submit a rating after a completed trip.
     */
    public function store(Request $request, Trip $trip): JsonResponse
    {
        abort_unless($trip->status === 'completed', 422, 'Unaweza kupiga kura baada tu ya safari kukamilika.');

        $user = $request->user();
        $isDriver = $trip->driver_id === $user->id;
        $isRider  = $trip->bookings()
            ->where('rider_id', $user->id)
            ->where('status', 'completed')
            ->exists();

        abort_unless($isDriver || $isRider, 403);

        $request->validate([
            'overall_rating'       => 'required|numeric|min:1|max:5',
            'rating_punctuality'   => 'nullable|integer|min:1|max:5',
            'rating_safety'        => 'nullable|integer|min:1|max:5',
            'rating_comfort'       => 'nullable|integer|min:1|max:5',
            'rating_communication' => 'nullable|integer|min:1|max:5',
            'comment'              => 'nullable|string|max:500',
        ]);

        $role       = $isDriver ? 'driver_review' : 'rider_review';
        $revieweeId = $isDriver ? $this->riderIdFromTrip($trip, $request) : $trip->driver_id;

        // Prevent duplicate review
        $exists = Review::where('trip_id', $trip->id)
            ->where('reviewer_id', $user->id)
            ->where('role', $role)
            ->exists();

        abort_if($exists, 422, 'Umeshatoa ukaguzi kwa safari hii.');

        $review = DB::transaction(function () use ($request, $trip, $user, $role, $revieweeId) {
            $review = Review::create([
                'trip_id'              => $trip->id,
                'reviewer_id'          => $user->id,
                'reviewee_id'          => $revieweeId,
                'role'                 => $role,
                'overall_rating'       => $request->overall_rating,
                'rating_punctuality'   => $request->rating_punctuality,
                'rating_safety'        => $request->rating_safety,
                'rating_comfort'       => $request->rating_comfort,
                'rating_communication' => $request->rating_communication,
                'comment'              => $request->comment,
            ]);

            // Recalculate reviewee's average rating
            $this->recalculateRating($revieweeId);

            return $review;
        });

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

    private function riderIdFromTrip(Trip $trip, Request $request): int
    {
        // Driver reviews a specific rider (optional rider_id param)
        if ($request->has('rider_id')) {
            return (int) $request->rider_id;
        }
        // Default: review the first confirmed rider
        return $trip->confirmedBookings()->first()?->rider_id ?? 0;
    }

    private function recalculateRating(int $userId): void
    {
        $avg = Review::where('reviewee_id', $userId)->avg('overall_rating');
        \App\Models\User::where('id', $userId)->update(['rating_avg' => round((float) $avg, 2)]);
    }
}
