<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\OAuthSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Inertia\Inertia;
use Inertia\Response;

class OAuthSettingsController extends Controller
{
    /**
     * Display the OAuth settings page.
     */
    public function index(): Response
    {
        $googleSetting = OAuthSetting::where('provider', 'google')->first();
        
        // Get the decrypted client_id for display (masked for security)
        $clientId = null;
        if ($googleSetting && !empty($googleSetting->client_id)) {
            try {
                $decryptedId = $googleSetting->getDecryptedClientId();
                // Mask the client ID for display, showing only first 15 chars
                if ($decryptedId && strlen($decryptedId) > 15) {
                    $clientId = substr($decryptedId, 0, 15) . '...';
                } else {
                    $clientId = $decryptedId;
                }
            } catch (\Exception $e) {
                $clientId = '(configurado)';
            }
        }

        return Inertia::render('Admin/Settings/OAuth', [
            'googleSettings' => [
                'client_id' => $clientId,
                'is_enabled' => $googleSetting?->is_enabled ?? false,
                'has_credentials' => $googleSetting && 
                    !empty($googleSetting->client_id) && 
                    !empty($googleSetting->client_secret),
                'scopes' => $googleSetting?->scopes ?? ['openid', 'profile', 'email'],
            ],
            'callbackUrl' => route('auth.google.callback'),
        ]);
    }

    /**
     * Update Google OAuth settings.
     */
    public function updateGoogle(Request $request)
    {
        $validated = $request->validate([
            'client_id' => 'nullable|string|max:500',
            'client_secret' => 'nullable|string|max:500',
            'is_enabled' => 'boolean',
        ]);

        $setting = OAuthSetting::firstOrCreate(
            ['provider' => 'google'],
            ['scopes' => ['openid', 'profile', 'email']]
        );

        // Build update data
        $updateData = ['is_enabled' => $validated['is_enabled'] ?? false];

        // Only update credentials if new values provided (not empty)
        // The model mutators will handle encryption automatically
        if (!empty($validated['client_id'])) {
            $updateData['client_id'] = $validated['client_id'];
        }

        if (!empty($validated['client_secret'])) {
            $updateData['client_secret'] = $validated['client_secret'];
        }

        // Update using fill to trigger model mutators for encryption
        $setting->fill($updateData);
        $setting->save();

        // Clear cache
        Cache::forget('oauth_setting_google');

        return back()->with('success', 'Configuración de Google OAuth actualizada correctamente.');
    }

    /**
     * Test Google OAuth connection.
     */
    public function testGoogle()
    {
        $setting = OAuthSetting::where('provider', 'google')->first();

        if (!$setting || empty($setting->client_id) || empty($setting->client_secret)) {
            return response()->json([
                'success' => false,
                'message' => 'Credenciales de Google no configuradas.',
            ]);
        }

        try {
            // Get decrypted credentials
            $clientId = $setting->getDecryptedClientId();
            $clientSecret = $setting->getDecryptedClientSecret();

            if (empty($clientId) || empty($clientSecret)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error al descifrar las credenciales.',
                ]);
            }

            // Basic validation of Client ID format (should end with .apps.googleusercontent.com)
            if (!str_ends_with($clientId, '.apps.googleusercontent.com')) {
                return response()->json([
                    'success' => false,
                    'message' => 'El Client ID no parece tener el formato correcto de Google.',
                ]);
            }

            return response()->json([
                'success' => true,
                'message' => 'Las credenciales parecen válidas. Prueba el flujo de login para verificar completamente.',
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error al validar credenciales: ' . $e->getMessage(),
            ]);
        }
    }

    /**
     * Remove Google OAuth credentials.
     */
    public function removeGoogle()
    {
        $setting = OAuthSetting::where('provider', 'google')->first();

        if ($setting) {
            $setting->update([
                'client_id' => null,
                'client_secret' => null,
                'is_enabled' => false,
            ]);
            Cache::forget('oauth_setting_google');
        }

        return back()->with('success', 'Credenciales de Google eliminadas correctamente.');
    }
}
