<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;

class CloudflareCredential extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'name',
        'api_token',
        'account_id',
        'email',
        'is_active',
        'is_verified',
        'verified_at',
        'last_used_at',
        'permissions',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'is_verified' => 'boolean',
        'verified_at' => 'datetime',
        'last_used_at' => 'datetime',
        'permissions' => 'array',
    ];

    protected $hidden = [
        'api_token',
    ];

    /**
     * Encrypt API token when setting
     */
    public function setApiTokenAttribute($value)
    {
        $this->attributes['api_token'] = Crypt::encryptString($value);
    }

    /**
     * Decrypt API token when getting
     */
    public function getApiTokenAttribute($value)
    {
        try {
            return Crypt::decryptString($value);
        } catch (\Exception $e) {
            return $value;
        }
    }

    /**
     * Get masked token for display
     */
    public function getMaskedTokenAttribute(): string
    {
        $token = $this->api_token;
        if (strlen($token) > 8) {
            return substr($token, 0, 4) . '****' . substr($token, -4);
        }
        return '****';
    }

    /**
     * Relatie cu utilizatorul
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Relatie cu zonele Cloudflare
     */
    public function zones()
    {
        return $this->hasMany(CloudflareZone::class, 'cloudflare_credential_id');
    }

    /**
     * Verifica daca este credentiala globala (admin)
     */
    public function isGlobal(): bool
    {
        return $this->user_id === null;
    }

    /**
     * Scope pentru credentiale active
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope pentru credentiale verificate
     */
    public function scopeVerified($query)
    {
        return $query->where('is_verified', true);
    }

    /**
     * Scope pentru credentiale globale
     */
    public function scopeGlobal($query)
    {
        return $query->whereNull('user_id');
    }

    /**
     * Scope pentru credentiale user
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Marcheaza ca verificat
     */
    public function markAsVerified(array $permissions = []): void
    {
        $this->update([
            'is_verified' => true,
            'verified_at' => now(),
            'permissions' => $permissions,
        ]);
    }

    /**
     * Marcheaza ca utilizat
     */
    public function markAsUsed(): void
    {
        $this->update(['last_used_at' => now()]);
    }

    /**
     * Obtine toate credentialele disponibile pentru un user
     * Include: propriile + globale
     */
    public static function getAvailableForUser(?int $userId): \Illuminate\Database\Eloquent\Collection
    {
        return self::active()
            ->verified()
            ->where(function ($query) use ($userId) {
                $query->whereNull('user_id') // Global
                      ->orWhere('user_id', $userId); // User's own
            })
            ->get();
    }
}
