<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Group;
use App\Services\GroupFollowService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GroupEngagementController extends Controller
{
    public function __construct(
        private readonly GroupFollowService $follows,
    ) {
    }

    public function follow(Request $request, Group $group): JsonResponse
    {
        $this->authorize('view', $group);

        $this->follows->follow($group, $request->user());

        return response()->json([
            'ok' => true,
            'following' => true,
            'followers_count' => (int) $group->fresh()->followers_count,
        ]);
    }

    public function unfollow(Request $request, Group $group): JsonResponse
    {
        $this->authorize('view', $group);

        $this->follows->unfollow($group, $request->user());

        return response()->json([
            'ok' => true,
            'following' => false,
            'followers_count' => (int) $group->fresh()->followers_count,
        ]);
    }
}