<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Group;
use App\Models\GroupFollow;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class GroupFollowService
{
    public function follow(Group $group, User $user): bool
    {
        if ($group->hasActiveMember($user)) {
            return false;
        }

        return DB::transaction(function () use ($group, $user): bool {
            $created = GroupFollow::query()->firstOrCreate([
                'group_id' => $group->id,
                'user_id' => $user->id,
            ]);

            $this->syncFollowerCount($group);

            return $created->wasRecentlyCreated;
        });
    }

    public function unfollow(Group $group, User $user): bool
    {
        $deleted = GroupFollow::query()
            ->where('group_id', $group->id)
            ->where('user_id', $user->id)
            ->delete() > 0;

        if ($deleted) {
            $this->syncFollowerCount($group);
        }

        return $deleted;
    }

    public function isFollowing(Group $group, ?User $user): bool
    {
        if (! $user) {
            return false;
        }

        return GroupFollow::query()
            ->where('group_id', $group->id)
            ->where('user_id', $user->id)
            ->exists();
    }

    public function syncFollowerCount(Group $group): void
    {
        $group->forceFill([
            'followers_count' => GroupFollow::query()->where('group_id', $group->id)->count(),
            'last_activity_at' => now(),
        ])->save();
    }
}