<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Boost;
use App\Models\Listing;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class BoostController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $boosts = Boost::with('listing.primaryImage')
            ->where('user_id', $request->user()->id)
            ->latest()
            ->get();

        foreach ($boosts as $boost) {
            $highest = Boost::where('city', $boost->city)->where('status', 'active')->max('bid_amount') ?? 0;
            $boost->highest_bid_in_city = $highest;
            $boost->is_outbid = ($highest > $boost->bid_amount) && ($boost->status === 'active');
        }

        return response()->json($boosts);
    }

    public function highest(Request $request): JsonResponse
    {
        $city = $request->query('city');
        if (!$city) {
            return response()->json(['highest_bid' => 0]);
        }
        $highest = Boost::where('city', $city)->where('status', 'active')->max('bid_amount') ?? 0;
        return response()->json(['highest_bid' => $highest]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'listing_id' => 'required|exists:listings,id',
            'city'       => 'required|string|max:100',
            'bid_amount' => 'required|numeric|min:1',
        ]);

        // Verify listing belongs to user
        $listing = Listing::where('id', $data['listing_id'])
            ->where('user_id', $request->user()->id)
            ->where('status', 'active')
            ->firstOrFail();

        $wallet = $request->user()->wallet;
        if (!$wallet || $wallet->balance < $data['bid_amount']) {
            return response()->json([
                'message' => 'Insufficient wallet balance. Please top up to place this bid.',
            ], 402);
        }

        $highestQuery = Boost::where('city', $data['city'])->where('status', 'active');
        $existingBoost = Boost::where('listing_id', $data['listing_id'])->where('city', $data['city'])->first();
        if ($existingBoost) {
            $highestQuery->where('id', '!=', $existingBoost->id);
        }
        $highest = $highestQuery->max('bid_amount') ?? 0;

        if ($data['bid_amount'] > $highest && $highest > 0) {
            if ($data['bid_amount'] < ($highest + 25)) {
                return response()->json([
                    'message' => "To take the top spot, you must outbid the next highest bid (₹{$highest}) by at least ₹25. Minimum bid required: ₹" . ($highest + 25),
                ], 422);
            }
        }

        // Upsert: update bid if already exists, otherwise create
        $boost = Boost::updateOrCreate(
            ['listing_id' => $data['listing_id'], 'city' => $data['city']],
            [
                'user_id'    => $request->user()->id,
                'bid_amount' => $data['bid_amount'],
                'status'     => 'active',
                'started_at' => now(),
            ]
        );

        return response()->json([
            'message' => 'Boost activated! Your listing will appear above others in ' . $data['city'] . '.',
            'boost'   => $boost,
        ], 201);
    }

    public function update(Request $request, Boost $boost): JsonResponse
    {
        if ($boost->user_id !== $request->user()->id) {
            abort(403);
        }

        $data = $request->validate([
            'bid_amount' => 'sometimes|numeric|min:1',
            'status'     => 'sometimes|in:active,paused',
        ]);

        // Validate wallet if increasing bid
        if (isset($data['bid_amount']) && $data['status'] !== 'paused') {
            $highest = Boost::where('city', $boost->city)
                ->where('status', 'active')
                ->where('id', '!=', $boost->id)
                ->max('bid_amount') ?? 0;
            
            if ($data['bid_amount'] > $highest && $highest > 0) {
                if ($data['bid_amount'] < ($highest + 25)) {
                    return response()->json([
                        'message' => "To take the top spot, your bid must be at least ₹25 higher than the next highest bid (₹{$highest}). Minimum bid required: ₹" . ($highest + 25),
                    ], 422);
                }
            }

            $wallet = $request->user()->wallet;
            if (!$wallet || $wallet->balance < $data['bid_amount']) {
                return response()->json(['message' => 'Insufficient wallet balance.'], 402);
            }
        }

        $boost->update($data);

        return response()->json(['message' => 'Boost updated.', 'boost' => $boost]);
    }

    public function destroy(Boost $boost): JsonResponse
    {
        if ($boost->user_id !== request()->user()->id) {
            abort(403);
        }
        $boost->delete();
        return response()->json(['message' => 'Boost removed.']);
    }
}
