<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;

class OAuthSetting extends Model
{
    protected $table = 'oauth_settings';

    protected $fillable = [
        'provider',
        'client_id',
        'client_secret',
        'is_enabled',
        'scopes',
        'additional_config',
    ];

    protected $casts = [
        'is_enabled' => 'boolean',
        'scopes' => 'array',
        'additional_config' => 'array',
    ];

    /**
     * Get the setting for a specific provider.
     */
    public static function getProvider(string $provider): ?self
    {
        return Cache::remember("oauth_setting_{$provider}", 3600, function () use ($provider) {
            return self::where('provider', $provider)->first();
        });
    }

    /**
     * Check if a provider is enabled.
     */
    public static function isProviderEnabled(string $provider): bool
    {
        $setting = self::getProvider($provider);
        
        if (!$setting) {
            return false;
        }

        return $setting->is_enabled && 
               !empty($setting->client_id) && 
               !empty($setting->client_secret);
    }

    /**
     * Get decrypted client ID.
     */
    public function getDecryptedClientId(): ?string
    {
        if (empty($this->client_id)) {
            return null;
        }

        try {
            return Crypt::decryptString($this->client_id);
        } catch (\Exception $e) {
            // If not encrypted (legacy), return as is
            return $this->client_id;
        }
    }

    /**
     * Get decrypted client secret.
     */
    public function getDecryptedClientSecret(): ?string
    {
        if (empty($this->client_secret)) {
            return null;
        }

        try {
            return Crypt::decryptString($this->client_secret);
        } catch (\Exception $e) {
            // If not encrypted (legacy), return as is
            return $this->client_secret;
        }
    }

    /**
     * Set encrypted client ID.
     */
    public function setClientIdAttribute($value): void
    {
        $this->attributes['client_id'] = $value ? Crypt::encryptString($value) : null;
    }

    /**
     * Set encrypted client secret.
     */
    public function setClientSecretAttribute($value): void
    {
        $this->attributes['client_secret'] = $value ? Crypt::encryptString($value) : null;
    }

    /**
     * Clear the cache for this provider.
     */
    public function clearCache(): void
    {
        Cache::forget("oauth_setting_{$this->provider}");
    }

    /**
     * Boot the model.
     */
    protected static function booted(): void
    {
        static::saved(function ($setting) {
            $setting->clearCache();
        });

        static::deleted(function ($setting) {
            $setting->clearCache();
        });
    }

    /**
     * Get Google configuration for Socialite.
     */
    public static function getGoogleConfig(): array
    {
        $setting = self::getProvider('google');

        if (!$setting || !$setting->is_enabled) {
            return [];
        }

        return [
            'client_id' => $setting->getDecryptedClientId(),
            'client_secret' => $setting->getDecryptedClientSecret(),
            'redirect' => route('auth.google.callback'),
        ];
    }
}
