<?php

namespace App\Services;

use App\Models\FeatureFlag;
use App\Models\User;

class FeatureGateService
{
    public function isEnabled(string $featureKey, ?User $user = null): bool
    {
        $global = FeatureFlag::query()
            ->where('scope', 'global')
            ->where('feature_key', $featureKey)
            ->value('is_enabled');

        if ($global !== null && ! (bool) $global) {
            return false;
        }

        if (! $user) {
            return $global ?? true;
        }

        $userFlag = FeatureFlag::query()
            ->where('scope', 'user')
            ->where('user_id', $user->id)
            ->where('feature_key', $featureKey)
            ->value('is_enabled');

        if ($userFlag !== null) {
            return (bool) $userFlag;
        }

        return $global ?? true;
    }
}
