<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
use Symfony\Component\HttpFoundation\RedirectResponse as SymfonyRedirectResponse;
use Throwable;

class GoogleAuthController extends Controller
{
    public function redirect(): SymfonyRedirectResponse
    {
        return Socialite::driver('google')
            ->scopes(['openid', 'profile', 'email'])
            ->redirect();
    }

    public function callback(): RedirectResponse
    {
        try {
            $googleUser = Socialite::driver('google')->user();
        } catch (Throwable) {
            return redirect()
                ->route('login')
                ->withErrors(['email' => 'Google login failed. Please try again.']);
        }

        $email = Str::lower($googleUser->getEmail());

        if (blank($email)) {
            return redirect()
                ->route('login')
                ->withErrors(['email' => 'Google did not return an email address.']);
        }

        $emailIsVerified = (bool) data_get($googleUser->user, 'email_verified', false);

        $user = User::where('google_id', $googleUser->getId())
            ->orWhere('email', $email)
            ->first();

        if ($user?->isBlocked()) {
            return redirect()
                ->route('login')
                ->withErrors(['email' => 'Your account has been blocked. Please contact support.']);
        }

        if ($user) {
            $updates = [
                'google_id' => $user->google_id ?: $googleUser->getId(),
                'avatar' => $googleUser->getAvatar(),
            ];

            if ($emailIsVerified && blank($user->email_verified_at)) {
                $updates['email_verified_at'] = now();
            }

            $user->update($updates);
        } else {
            $user = User::create([
                'name' => $googleUser->getName() ?: Str::before($email, '@'),
                'email' => $email,
                'google_id' => $googleUser->getId(),
                'avatar' => $googleUser->getAvatar(),
                'email_verified_at' => $emailIsVerified ? now() : null,
                'password' => Hash::make(Str::random(64)),
                'role' => 'user',
                'status' => 'active',
            ]);

            event(new Registered($user));
        }

        Auth::login($user, remember: true);

        return redirect()->intended($this->redirectPathFor($user));
    }

    private function redirectPathFor(User $user): string
    {
        if ($user->isAdmin()) {
            return route('admin.dashboard', absolute: false);
        }

        if ($user->isSupportTeam()) {
            return route('support-team.dashboard', absolute: false);
        }

        return route('dashboard', absolute: false);
    }
}
