<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Community;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\PostComment;
use App\Models\PostReaction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class PostReactionController extends Controller
{
    public function togglePost(Request $request, string $postId): JsonResponse
    {
        $user = $request->user();
        if (! $user) throw new AccessDeniedHttpException('LOGIN_REQUIRED');

        $post = Post::findOrFail($postId);
        $type = $request->input('type', 'like');
        if (! in_array($type, ['like', 'dislike'], true)) $type = 'like';

        $existing = PostReaction::where('user_id', $user->id)
            ->where('post_id', $post->id)
            ->where('type', $type)
            ->first();

        if ($existing) {
            $existing->delete();
            if ($type === 'like') $post->decrement('like_count');
            $action = 'removed';
        } else {
            PostReaction::create([
                'post_id' => $post->id,
                'user_id' => $user->id,
                'type' => $type,
            ]);
            if ($type === 'like') $post->increment('like_count');
            $action = 'added';
        }

        return response()->json([
            'data' => [
                'action' => $action,
                'type' => $type,
                'like_count' => $post->fresh()->like_count,
            ],
        ]);
    }

    public function toggleComment(Request $request, string $commentId): JsonResponse
    {
        $user = $request->user();
        if (! $user) throw new AccessDeniedHttpException('LOGIN_REQUIRED');

        $comment = PostComment::findOrFail($commentId);
        $type = $request->input('type', 'like');
        if (! in_array($type, ['like', 'dislike'], true)) $type = 'like';

        $existing = PostReaction::where('user_id', $user->id)
            ->where('comment_id', $comment->id)
            ->where('type', $type)
            ->first();

        if ($existing) {
            $existing->delete();
            if ($type === 'like') $comment->decrement('like_count');
            $action = 'removed';
        } else {
            PostReaction::create([
                'comment_id' => $comment->id,
                'user_id' => $user->id,
                'type' => $type,
            ]);
            if ($type === 'like') $comment->increment('like_count');
            $action = 'added';
        }

        return response()->json([
            'data' => [
                'action' => $action,
                'type' => $type,
                'like_count' => $comment->fresh()->like_count,
            ],
        ]);
    }
}
