<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductFavorite;
use Illuminate\Http\Request;

class ProductFavoriteController extends Controller
{
    public function toggle(Request $request)
    {
        if (! auth()->check()) {
            return response()->json([
                'favorited' => false,
                'login_required' => true,
                'login_url' => url('/login'),
            ], 401);
        }

        $request->validate([
            'product_id' => 'required|integer',
        ]);

        $productId = (int) $request->input('product_id');

        $product = Product::where('id', $productId)
            ->where('status', Product::$active)
            ->where('ordering', true)
            ->first();

        if (empty($product)) {
            return response()->json([
                'favorited' => false,
                'error' => 'not_found',
            ], 404);
        }

        $userId = auth()->id();

        $existing = ProductFavorite::where('user_id', $userId)
            ->where('product_id', $productId)
            ->first();

        if (! empty($existing)) {
            $existing->delete();

            return response()->json([
                'favorited' => false,
                'product_id' => $productId,
            ]);
        }

        ProductFavorite::create([
            'user_id' => $userId,
            'product_id' => $productId,
        ]);

        return response()->json([
            'favorited' => true,
            'product_id' => $productId,
        ]);
    }
}
