<?php

namespace App\Domains\Subscription\Services;

use App\Domains\Subscription\Models\Plan;
use App\Domains\Workspace\Models\Workspace;
use Illuminate\Support\Facades\Redis;

class PlanLimitsService
{
    public function canCreateLink(Workspace $workspace): bool
    {
        /** @var Plan|null $plan */
        $plan = $workspace->plan;
        if (! $plan) {
            return true; // No plan = allow (trial or free)
        }
        $count = $workspace->links()->count();

        return $count < $plan->link_limit;
    }

    public function monthlyClicksUsed(Workspace $workspace): int
    {
        $key = "clicks:{$workspace->id}:monthly:".now()->format('Ym');

        return (int) Redis::get($key);
    }

    public function isClickLimitApproaching(Workspace $workspace): bool
    {
        /** @var Plan|null $plan */
        $plan = $workspace->plan;
        if (! $plan) {
            return false;
        }
        $used = $this->monthlyClicksUsed($workspace);

        return $used >= ($plan->click_limit_monthly * 0.9);
    }

    public function isClickLimitExceeded(Workspace $workspace): bool
    {
        /** @var Plan|null $plan */
        $plan = $workspace->plan;
        if (! $plan) {
            return false;
        }

        return $this->monthlyClicksUsed($workspace) >= $plan->click_limit_monthly;
    }
}
