<?php

namespace App\Modules\Dashboard\Repositories;

use App\Modules\Admin\Tenancy\Models\Subscription;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Admin\Tenancy\Services\SubscriptionService;
use App\Modules\Admin\Tenancy\Support\PlanLimitKeys;
use App\Modules\HR\Employees\Models\Employee as HrEmployee;

class TenantBillingSignalsRepository
{
    public function __construct(
        private readonly SubscriptionService $subscriptions,
    ) {}

    public function subscriptionIssueCount(Tenant $tenant): int
    {
        $sub = $tenant->activeSubscription ?? $this->subscriptions->activeFor($tenant);
        if ($sub === null) {
            return 1;
        }
        $n = 0;
        if ($sub->status === Subscription::STATUS_EXPIRED) {
            $n++;
        }
        if ($sub->status === Subscription::STATUS_TRIAL && $sub->trial_ends_at !== null) {
            if (! $sub->trial_ends_at->isFuture()) {
                $n++;
            } elseif (now()->startOfDay()->diffInDays($sub->trial_ends_at->copy()->startOfDay(), false) <= 7) {
                $n++;
            }
        }
        if ($sub->status === Subscription::STATUS_GRACE_PERIOD && $sub->grace_ends_at !== null) {
            if ($sub->grace_ends_at->isFuture()
                && now()->startOfDay()->diffInDays($sub->grace_ends_at->copy()->startOfDay(), false) <= 3) {
                $n++;
            }
        }

        return $n;
    }

    public function planLimitRiskCount(Tenant $tenant): int
    {
        $plan = $tenant->activeSubscription?->plan ?? $tenant->plan;
        if ($plan === null) {
            return 0;
        }
        $limitRow = $plan->limits()
            ->where('key', PlanLimitKeys::EMPLOYEES_LIMIT)
            ->where('is_enabled', true)
            ->first();
        if ($limitRow === null || (int) $limitRow->limit <= 0) {
            return 0;
        }
        $limit = (int) $limitRow->limit;
        $count = HrEmployee::query()->where('tenant_id', $tenant->id)->where('is_active', true)->count();
        if ($count >= $limit) {
            return 1;
        }
        if ($count >= (int) floor($limit * 0.9)) {
            return 1;
        }

        return 0;
    }
}
