<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;

class SocialAuthController extends Controller
{
    private const ALLOWED_PROVIDERS = ['google'];

    public function redirect(string $provider)
    {
        if (! in_array($provider, self::ALLOWED_PROVIDERS, true)) {
            abort(404);
        }

        if (! $this->providerIsConfigured($provider)) {
            return redirect()
                ->back(fallback: route('login'))
                ->with('error', 'Google sign-in is not configured yet. Please use email and password, or ask the site admin to add Google OAuth credentials.');
        }

        return Socialite::driver($provider)->redirect();
    }

    public function callback(string $provider)
    {
        if (! in_array($provider, self::ALLOWED_PROVIDERS, true)) {
            abort(404);
        }

        if (! $this->providerIsConfigured($provider)) {
            return redirect()
                ->route('login')
                ->with('error', 'Google sign-in is not configured yet. Please use email and password.');
        }

        try {
            $socialUser = Socialite::driver($provider)->user();
        } catch (\Throwable $e) {
            Log::warning('Social login failed', [
                'provider' => $provider,
                'message' => $e->getMessage(),
            ]);

            return redirect()
                ->route('login')
                ->with('error', 'Unable to sign in with Google. Please try again or use email and password.');
        }

        if (! $socialUser->getEmail()) {
            return redirect()
                ->route('login')
                ->with('error', 'Google did not provide an email address for this account. Please register with email instead.');
        }

        $user = User::where('provider_id', $socialUser->getId())
            ->orWhere('email', $socialUser->getEmail())
            ->first();

        if (! $user) {
            $user = User::create([
                'name' => $socialUser->getName() ?? $socialUser->getNickname() ?? 'Google User',
                'email' => $socialUser->getEmail(),
                'provider' => $provider,
                'provider_id' => $socialUser->getId(),
                'avatar' => $socialUser->getAvatar(),
                'password' => Hash::make(Str::random(24)),
                'email_verified_at' => now(),
            ]);
        } else {
            $user->update([
                'provider' => $provider,
                'provider_id' => $socialUser->getId(),
                'avatar' => $user->avatar ?? $socialUser->getAvatar(),
                'email_verified_at' => $user->email_verified_at ?? now(),
            ]);
        }

        Auth::login($user, true);

        if ($user->is_admin) {
            return redirect()->intended(route('admin.dashboard'))->with('success', 'Welcome back, Admin!');
        }

        return redirect()->intended(route('home'))->with('success', 'Logged in successfully!');
    }

    private function providerIsConfigured(string $provider): bool
    {
        if ($provider !== 'google') {
            return false;
        }

        return filled(config('services.google.client_id'))
            && filled(config('services.google.client_secret'));
    }
}
