<?php

namespace App\Services\Keywords;

use App\Models\UserKeyword;

class KeywordQuotaService
{
    public function freeActiveLimit(): int
    {
        return max((int) config('dewemoji.pagination.free_max_limit', 20), 1);
    }

    public function activeCount(int $userId): int
    {
        return UserKeyword::query()
            ->where('user_id', $userId)
            ->where('is_active', true)
            ->count();
    }

    public function canActivateMore(int $userId): bool
    {
        return $this->activeCount($userId) < $this->freeActiveLimit();
    }

    public function enforceForUser(int $userId, string $tier): void
    {
        if ($tier === 'personal') {
            UserKeyword::query()
                ->where('user_id', $userId)
                ->where('is_active', false)
                ->update(['is_active' => true]);

            return;
        }

        $limit = $this->freeActiveLimit();
        $activeIds = UserKeyword::query()
            ->where('user_id', $userId)
            ->where('is_active', true)
            ->orderBy('created_at')
            ->orderBy('id')
            ->pluck('id')
            ->all();

        if (count($activeIds) <= $limit) {
            return;
        }

        $keep = array_slice($activeIds, 0, $limit);
        UserKeyword::query()
            ->where('user_id', $userId)
            ->where('is_active', true)
            ->whereNotIn('id', $keep)
            ->update(['is_active' => false]);
    }
}
