<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Resources\FavoritePaginationResource;
use App\Models\Currency;
use App\Models\Favorite;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FavoriteController extends Controller
{
    public function index(Request $request)
    {
        $currency = Currency::latest()->first();
        // add currency to cache
        cache()->put('currency', $currency, now()->addMinutes(60));

        $user = $request->user();
        $favorites = Favorite::where('user_id', $user->id)->whereHas('product', function ($q) {
            $q->whereNull('child_id');
        })->paginate($request->limit ?? 10);

        return (new FavoritePaginationResource($favorites))->response();
    }

    public function store(Request $request, $product_id)
    {
        $product = Product::findOrFail($product_id);

        $user = $request->user();

        // check if product already in favorites
        $favorite = Favorite::where('user_id', $user->id)->where('product_id', $product_id)->first();

        if (!$favorite) {
            Favorite::create([
                'user_id' => $user->id,
                'product_id' => $product_id
            ]);
        }

        return response()->json([
            'message' => 'Successfully added to favorites'
        ])->setStatusCode(200);
    }

    public function destroy(Request $request, $product_id)
    {
        try {
            DB::beginTransaction();
            $user = $request->user();

            Favorite::where('user_id', $user->id)->where('product_id', $product_id)->delete();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage()])->setStatusCode(500);
        }

        return response('', 204);
    }
}
