<?php

namespace App\Serp\Operations;

use App\Models\SerpOperationState;
use Throwable;

final class ActivationManager
{
    public function state(): ActivationState
    {
        try {
            $configured = ActivationState::tryFrom((string) config('serp.operation_mode'));
            if (! $configured) {
                return ActivationState::Disabled;
            }$db = SerpOperationState::query()->find(1);
            if ($db?->emergency_stopped_at) {
                return ActivationState::EmergencyStopped;
            }

return $configured;
        } catch (Throwable) {
            return ActivationState::Disabled;
        }
    }

    public function allowsNormal(): bool
    {
        return config('serp.enabled') === true && config('serp.provider') === 'dataforseo' && $this->state() === ActivationState::Enabled;
    }

    public function allowsCanary(): bool
    {
        return config('serp.enabled') === true && config('serp.provider') === 'dataforseo' && $this->state() === ActivationState::Canary;
    }

    public function allowsPaid(bool $canary = false): bool
    {
        return $canary ? $this->allowsCanary() : $this->allowsNormal();
    }

    public function assertPaid(bool $canary = false): void
    {
        if (! $this->allowsPaid($canary)) {
            throw new OperationBlockedException($this->state() === ActivationState::EmergencyStopped ? 'emergency_stopped' : 'activation_blocked');
        }
    }
}
