<?php

namespace App\Http\Controllers\Api\V1\Client\Profile;

use App\Http\Controllers\Controller;
use App\Models\Contest;
use App\Models\Quiz;
use App\Services\ModalIndexQuey;
use App\Traits\Formatter;
use Illuminate\Http\Request;

class FavoriteController extends Controller
{
    use Formatter;

    /**
     * @OA\Get(
     *     path="/api/v1/profile/favorites",
     *     summary="Get favorite list",
     *     description="Get favorite list by user",
     *     tags={"dashboard"},
     *
     *     @OA\Response(
     *         response=200,
     *         description="favorite list fetched successfully",
     *
     *         @OA\JsonContent(
     *             type="object",
     *
     *             @OA\Property(property="statusCode", type="number", example=200),
     *             @OA\Property(property="data", type="array",
     *
     *                 @OA\Items(
     *                     type="object",
     *
     *                     @OA\Property(property="id", type="string"),
     *                     @OA\Property(property="symbol_position", type="string"),
     *                     @OA\Property(property="symbol", type="string"),
     *                     @OA\Property(property="rate", type="number")
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function index()
    {
        /**
         * @var \App\Models\User $user
         */
        $user = auth('client')->user();

        $type = request('type', 'quiz');

        $modelClass = $type === 'quiz' ? Quiz::class : Contest::class;

        $query = $modelClass::whereHas('favorites', function ($query) use ($user) {
            $query->where('user_id', $user->id);
        });

        if ($type === 'contest') {
            $query->withCount([
                'questions',
                'participants',
            ])
                ->withSum('questions', 'time_limit');
        } else {
            $query->withSum('questions', 'time_limit')
                ->withCount(['QuestionLevels', 'questions', 'userQuizzes'])
                ->with([
                    'userQuizzes' => fn ($query) => $query->with('user:id,avatar')->limit(3),
                ]);
        }

        $favorites = ModalIndexQuey::get(
            $query,
            ['category:id,title']
        );

        return $this->withSuccess($favorites);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'favorable_type' => 'required|string|in:quiz,contest',
            'slug' => 'required|string',
            'type' => 'required|in:add,remove',
        ]);

        /**
         * @var \App\Models\User $user
         */
        $user = $request->user('client');

        $favorable = null;

        $model = $validated['favorable_type'] == 'quiz' ? Quiz::query() : Contest::query();

        $favorable = $model->whereRelation('translations', 'slug', $validated['slug'])->firstOrFail();

        if ($request->type == 'remove') {
            $user->favorites()->where('favorable_id', $favorable->id)->delete();

            return response()->json([
                'status' => 'success',
                'message' => __(ucfirst($validated['favorable_type']).' removed from favorite successfully'),
            ]);
        }

        $already_exist = $user->favorites()->where('favorable_id', $favorable->id)->exists();
        if ($already_exist) {
            return response()->json([
                'status' => 'success',
                'message' => __(ucfirst($validated['favorable_type']).' already added to favorite'),
            ]);
        }

        $user->favorites()->create([
            'favorable_id' => $favorable->id,
            'favorable_type' => get_class($favorable),
        ]);

        return response()->json([
            'status' => 'success',
            'message' => __(ucfirst($validated['favorable_type']).' added to favorite successfully'),
        ]);
    }
}
