<?php

namespace App\Http\Controllers\Api;

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

class WaitlistController extends Controller
{
    public function subscribe(Request $request, Listing $listing): JsonResponse
    {
        $user = $request->user();

        $existing = ListingWaitlist::where('user_id', $user->id)
            ->where('listing_id', $listing->id)
            ->first();

        if ($existing) {
            return response()->json(['message' => 'Zaten bekleme listesinesiniz.'], 409);
        }

        ListingWaitlist::create([
            'user_id' => $user->id,
            'listing_id' => $listing->id,
        ]);

        return response()->json(['message' => 'Bekleme listesine eklendi.', 'subscribed' => true]);
    }

    public function unsubscribe(Request $request, Listing $listing): JsonResponse
    {
        $user = $request->user();

        $deleted = ListingWaitlist::where('user_id', $user->id)
            ->where('listing_id', $listing->id)
            ->delete();

        if (!$deleted) {
            return response()->json(['message' => 'Bekleme listesinde değilsiniz.'], 404);
        }

        return response()->json(['message' => 'Bekleme listesinden çıkarıldı.', 'subscribed' => false]);
    }

    public function status(Request $request, Listing $listing): JsonResponse
    {
        $user = $request->user();

        $subscribed = ListingWaitlist::where('user_id', $user->id)
            ->where('listing_id', $listing->id)
            ->exists();

        return response()->json(['subscribed' => $subscribed]);
    }
}
