<?php

namespace App\Http\Controllers\Integration;

use App\Http\Controllers\Controller;
use App\Models\CalendarIntegration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class GoogleCalendarController extends Controller
{
    private const AUTH_URL     = 'https://accounts.google.com/o/oauth2/v2/auth';
    private const TOKEN_URL    = 'https://oauth2.googleapis.com/token';
    private const USERINFO_URL = 'https://www.googleapis.com/oauth2/v3/userinfo';
    private const CALENDAR_URL = 'https://www.googleapis.com/calendar/v3/calendars/primary';

    public function redirect()
    {
        $state = Str::random(40);
        session(['google_oauth_state' => $state]);

        $query = http_build_query([
            'client_id'     => config('services.google_calendar.client_id'),
            'redirect_uri'  => config('services.google_calendar.redirect'),
            'response_type' => 'code',
            'scope'         => 'https://www.googleapis.com/auth/calendar openid email profile',
            'access_type'   => 'offline',
            'prompt'        => 'consent',
            'state'         => $state,
        ]);

        return redirect(self::AUTH_URL.'?'.$query);
    }

    public function callback(Request $request)
    {
        // CSRF-State prüfen
        if ($request->state !== session('google_oauth_state')) {
            return redirect()->route('integrations.index')
                ->with('integration_error', 'Ungültiger State-Parameter.');
        }

        if ($request->has('error')) {
            return redirect()->route('integrations.index')
                ->with('integration_error', 'Zugriff verweigert: '.$request->error);
        }

        // Code gegen Token tauschen
        $response = Http::asForm()->post(self::TOKEN_URL, [
            'code'          => $request->code,
            'client_id'     => config('services.google_calendar.client_id'),
            'client_secret' => config('services.google_calendar.client_secret'),
            'redirect_uri'  => config('services.google_calendar.redirect'),
            'grant_type'    => 'authorization_code',
        ]);

        if ($response->failed()) {
            return redirect()->route('integrations.index')
                ->with('integration_error', 'Token-Austausch fehlgeschlagen.');
        }

        $tokens = $response->json();

        // E-Mail des Google-Accounts holen
        $userInfo = Http::withToken($tokens['access_token'])
            ->get(self::USERINFO_URL)
            ->json();

        // Primären Kalender-Namen holen
        $calendarInfo = Http::withToken($tokens['access_token'])
            ->get(self::CALENDAR_URL)
            ->json();

        CalendarIntegration::updateOrCreate(
            ['user_id' => auth()->id(), 'provider' => 'google'],
            [
                'provider_email'   => $userInfo['email'] ?? null,
                'calendar_id'      => 'primary',
                'calendar_name'    => $calendarInfo['summary'] ?? 'Primärer Kalender',
                'access_token'     => $tokens['access_token'],
                'refresh_token'    => $tokens['refresh_token'] ?? null,
                'token_expires_at' => now()->addSeconds($tokens['expires_in'] ?? 3600),
            ]
        );

        return redirect()->route('integrations.index')
            ->with('integration_connected', 'google');
    }
}
