<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Group;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class GoogleController extends Controller
{
    /**
     * Arahkan user ke halaman consent Google.
     */
    public function redirect(): RedirectResponse
    {
        return Socialite::driver('google')->redirect();
    }

    /**
     * Callback Google: find-or-create user, login, redirect ke dashboard.
     */
    public function callback(): RedirectResponse
    {
        try {
            $googleUser = Socialite::driver('google')->user();
        } catch (\Throwable $e) {
            return redirect()->route('login')->with('error', 'Login Google gagal. Silakan coba lagi.');
        }

        if (! $googleUser->getEmail()) {
            return redirect()->route('login')->with('error', 'Akun Google tidak memiliki email.');
        }

        // Cari user by google_id atau email.
        $user = User::where('google_id', $googleUser->getId())
            ->orWhere('email', $googleUser->getEmail())
            ->first();

        if ($user) {
            // Catat google_id bila belum ada (link akun existing berdasarkan email).
            if (! $user->google_id) {
                $user->update(['google_id' => $googleUser->getId()]);
            }
        } else {
            // Buat user baru dari akun Google, assign grup members.
            $user = User::create([
                'name' => $googleUser->getName() ?? $googleUser->getNickname() ?? 'Google User',
                'email' => $googleUser->getEmail(),
                'google_id' => $googleUser->getId(),
                'password' => null,
                'credit' => 0,
                'status' => 'active',
                'email_verified_at' => now(),
            ]);

            $membersGroup = Group::where('name', Group::MEMBERS)->value('id')
                ?? Group::firstOrCreate(['name' => Group::MEMBERS])->id;
            $user->groups()->attach($membersGroup);
        }

        if (! $user->status->canLogin()) {
            return redirect()->route('login')->with('error', 'Akun Anda '.$user->status->label().'. Hubungi admin.');
        }

        Auth::login($user, true);

        return redirect()->intended(config('fortify.home', '/dashboard'));
    }
}
