<?php

namespace App\Http\Controllers;


use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;

class SocialAuthController extends Controller
{
    public function handleSocialLogin(Request $request)
    {
        $request->validate([
            'provider' => 'required|in:google,facebook',
            'token'    => 'required',
            'role'     => 'required|in:Buyer,Content Creator',
        ]);

        $providerUser = Socialite::driver($request->provider)->stateless()->userFromToken($request->token);

        $user = User::firstOrCreate([
            'email' => $providerUser->getEmail()
        ], [
            'name'        => $providerUser->getName(),
            'provider'    => $request->provider,
            'provider_id' => $providerUser->getId(),
            'email_verified_at' => now(),
            'password' => Hash::make(Str::random(24))
        ]);

        if (!$user->hasRole($request->role)) {
            $user->assignRole($request->role);
        }

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'message' => 'Logged in with ' . $request->provider,
            'token'   => $token,
            'role'    => $user->getRoleNames()
        ]);
    }
}
