<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class FeatureFlag extends Model
{
    use HasFactory;

    protected $fillable = [
        'key',
        'name',
        'description',
        'is_enabled',
        'target_users',
        'rollout_percentage',
        'starts_at',
        'ends_at',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'is_enabled' => 'boolean',
            'target_users' => 'array',
            'rollout_percentage' => 'decimal:2',
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
            'metadata' => 'array',
        ];
    }

    public function isActive(): bool
    {
        if (!$this->is_enabled) {
            return false;
        }

        $now = now();
        
        if ($this->starts_at && $now->lt($this->starts_at)) {
            return false;
        }

        if ($this->ends_at && $now->gt($this->ends_at)) {
            return false;
        }

        return true;
    }

    public function isEnabledForUser(?int $userId = null): bool
    {
        if (!$this->isActive()) {
            return false;
        }

        // Check if user is in target list
        if ($this->target_users && is_array($this->target_users)) {
            if ($userId && in_array($userId, $this->target_users)) {
                return true;
            }
            // If target_users is set but user not in list, return false
            if (!empty($this->target_users)) {
                return false;
            }
        }

        // Check rollout percentage
        if ($this->rollout_percentage > 0) {
            $hash = md5($this->key . ($userId ?? request()->ip()));
            $hashValue = hexdec(substr($hash, 0, 8));
            $percentage = ($hashValue % 10000) / 100;
            
            return $percentage < $this->rollout_percentage;
        }

        return true;
    }
}
