<?php

namespace App\Http\Controllers\Api;

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

class FavoriteController extends Controller
{
    /**
     * List user's favorite listings
     */
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        
        $favorites = Listing::whereHas('favorites', function ($query) use ($user) {
                $query->where('user_id', $user->id);
            })
            ->with(['listingType', 'city.province', 'coverImage', 'owner:id,name,avatar'])
            ->active()
            ->paginate(15);

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

    /**
     * Toggle favorite status for a listing
     */
    public function toggle(Listing $listing, Request $request): JsonResponse
    {
        $user = $request->user();
        
        $favorite = FavoriteListing::where('user_id', $user->id)
            ->where('listing_id', $listing->id)
            ->first();

        if ($favorite) {
            $favorite->delete();
            $isFavorited = false;
            $message = 'İlan favorilerinizden çıkarıldı.';
        } else {
            FavoriteListing::create([
                'user_id' => $user->id,
                'listing_id' => $listing->id,
            ]);
            $isFavorited = true;
            $message = 'İlan favorilerinize eklendi.';
        }

        return response()->json([
            'is_favorited' => $isFavorited,
            'message' => $message,
        ]);
    }
}
