<?php

namespace App\Core\License\Services;

use App\Core\License\Models\LicenseModel;
use App\Core\License\Models\UsageCounterModel;
use App\Core\Modules\Services\ModuleManager;
use App\Core\Auth\Models\UserModel;

class LicenseService
{
    public function current(): ?array
    {
        return (new LicenseModel())->orderBy('id', 'DESC')->first();
    }

    public function isValid(): bool
    {
        $license = $this->current();
        if (! $license || $license['status'] !== 'active') {
            return false;
        }

        return empty($license['expires_at']) || strtotime($license['expires_at']) >= time();
    }

    public function getPlan(): string
    {
        return $this->current()['plan'] ?? 'free';
    }

    public function canUseModule(string $module): bool
    {
        $license = $this->current();
        if (! $license || ! $this->isValid()) {
            return false;
        }

        $enabled = array_filter((new ModuleManager())->discover(), fn ($item) => ! empty($item['enabled']));

        return count($enabled) <= (int) $license['max_modules'];
    }

    public function canCreateUser(): bool
    {
        $license = $this->current();
        if (! $license || ! $this->isValid()) {
            return false;
        }

        return (new UserModel())->countAllResults() < (int) $license['max_users'];
    }

    public function canUseAi(): bool
    {
        $license = $this->current();
        if (! $license || ! $this->isValid()) {
            return false;
        }

        $counter = $this->counter('ai_requests');

        return (int) ($counter['value'] ?? 0) < (int) $license['max_ai_requests_month'];
    }

    public function incrementUsage(string $metric): void
    {
        $counters = new UsageCounterModel();
        $period = date('Y-m');
        $row = $counters->where('metric', $metric)->where('period', $period)->first();

        if ($row) {
            $counters->update($row['id'], ['value' => (int) $row['value'] + 1]);
        } else {
            $counters->insert(['metric' => $metric, 'period' => $period, 'value' => 1]);
        }
    }

    private function counter(string $metric): ?array
    {
        return (new UsageCounterModel())->where('metric', $metric)->where('period', date('Y-m'))->first();
    }
}
