<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Socialite\Facades\Socialite;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $messages = [
            'name.required' => 'The name field is required.',
            'email.required' => 'The email field is required.',
            'email.email' => 'The email must be a valid email address.',
            'email.unique' => 'The email has already been taken.',
            'phone_number.required' => 'The phone number field is required.',
            'phone_number.unique' => 'The phone number has already been taken.',
            'password.required' => 'The password field is required.',
            'password.min' => 'The password must be at least 6 characters.',
        ];

        $request->headers->set('Accept', 'application/json');

        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'phone_number' => 'required|unique:users,phone_number',
            'password' => 'required|min:6',
        ], $messages);

        try {
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'phone_number' => $request->phone_number,
                'password' => Hash::make($request->password),
            ]);

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

            return response()->json([
                'access_token' => $token,
                'token_type' => 'Bearer',
            ])->cookie('access_token', $token, 60 * 24, null, null, false, true);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to register user. Please try again.'], 500);
        }
    }

    public function login(Request $request)
    {
        $messages = [
            'email.required' => 'The email field is required.',
            'email.email' => 'The email must be a valid email address.',
            'password.required' => 'The password field is required.',
        ];

        $request->headers->set('Accept', 'application/json');

        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ], $messages);

        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json(['error' => 'Invalid login details'], 401);
        }

        try {
            $user = User::where('email', $request->email)->firstOrFail();
            $token = $user->createToken('auth_token')->plainTextToken;

            return response()->json([
                'access_token' => $token,
                'token_type' => 'Bearer',
            ])->cookie('access_token', $token, 60 * 24, null, null, false, true);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to login. Please try again.'], 500);
        }
    }

    public function logout()
    {
        try {
            auth()->user()->tokens()->delete();
            return response()->json(['message' => 'Logged out'], 200);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to logout. Please try again.'], 500);
        }
    }

    public function redirectToGoogle()
    {
        try {
            return Socialite::driver('google')->stateless()->redirect();
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to redirect to Google. Please try again.'], 500);
        }
    }

    public function handleGoogleCallback()
    {
        try {
            $googleUser = Socialite::driver('google')->stateless()->user();
            $user = User::firstOrCreate(
                ['email' => $googleUser->getEmail()],
                ['name' => $googleUser->getName(), 'password' => Hash::make(Str::random(24))]
            );

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

            return redirect('https://www.legitinfogames.com/signIn?token=' . $token);

        } catch (\Exception $e) {

            Log::error('Google OAuth error: ', ['exception' => $e]);
            return response()->json(['error' => 'Failed to authenticate. Please try again.'], 500);
        }
    }
}
