<?php

namespace App\Http\Controllers\Admin\Integrations;

use App\Http\Controllers\Controller;
use App\Models\PlatformConnection;
use App\Services\Credentials\CredentialVault;
use App\Services\Integrations\GoogleOAuthService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class GoogleOAuthController extends Controller
{
    public function redirect(PlatformConnection $connection, GoogleOAuthService $oauth): RedirectResponse
    {
        abort_unless(in_array($connection->platform, ['google_ads', 'search_console', 'ga4'], true), 404);

        try {
            return redirect()->away($oauth->authorizationUrl($connection->load('secureCredential')));
        } catch (\Throwable $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function callback(Request $request, GoogleOAuthService $oauth, CredentialVault $vault): RedirectResponse
    {
        if ($request->filled('error')) {
            return redirect()->route('admin.dashboard')->with('error', 'Google OAuth iptal/hata: '.$request->string('error'));
        }

        $expectedState = session('dw_google_oauth_state');
        $connectionId = session('dw_google_oauth_connection_id');

        if (! $expectedState || $request->string('state')->toString() !== $expectedState || ! $connectionId) {
            return redirect()->route('admin.dashboard')->with('error', 'Google OAuth state doğrulaması başarısız.');
        }

        $connection = PlatformConnection::with('secureCredential')->findOrFail($connectionId);

        try {
            $tokens = $oauth->exchangeCode($connection, $request->string('code')->toString());
            $vault->saveOAuthTokens($connection, $tokens);
            $connection->update([
                'status' => 'draft',
                'last_error' => null,
                'meta' => array_merge($connection->meta ?? [], [
                    'oauth_connected_at' => now()->toIso8601String(),
                    'oauth_scope' => $tokens['scope'] ?? null,
                ]),
            ]);

            session()->forget(['dw_google_oauth_state', 'dw_google_oauth_connection_id']);

            return redirect()
                ->route('admin.accounts.'.$this->routeKey($connection->platform).'.show', $connection)
                ->with('success', 'Google OAuth bağlantısı alındı. Şimdi Bağlantıyı Test Et butonuyla doğrulayabilirsin.');
        } catch (\Throwable $e) {
            return redirect()
                ->route('admin.accounts.'.$this->routeKey($connection->platform).'.show', $connection)
                ->with('error', $e->getMessage());
        }
    }

    private function routeKey(string $platform): string
    {
        return match ($platform) {
            'google_ads' => 'google-ads',
            'search_console' => 'search-console',
            'ga4' => 'ga4',
            default => $platform,
        };
    }
}
