<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\GoogleAuthRequest;
use App\Http\Resources\AuthResource;
use Google\Client as GoogleClient;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class GoogleAuthController extends Controller
{
    public function __invoke(GoogleAuthRequest $request): Response
    {
        $client = new GoogleClient(['client_id' => config('services.google.client_id')]);

        try {
            $payload = $client->verifyIdToken($request->validated('id_token'));
        } catch (\Exception $e) {
            Log::warning('Google token verification failed', ['exception' => $e->getMessage()]);

            return response(
                ['message' => 'Invalid Google token'],
                Response::HTTP_UNAUTHORIZED,
            );
        }

        if (! $payload) {
            return response(
                ['message' => 'Invalid Google token'],
                Response::HTTP_UNAUTHORIZED,
            );
        }

        $googleId = $payload['sub'] ?? null;
        $email = $payload['email'] ?? null;
        $firstName = $payload['given_name'] ?? null;
        $lastName = $payload['family_name'] ?? null;
        $pictureUrl = $payload['picture'] ?? null;

        if (! $googleId || ! $email) {
            return response(
                ['message' => 'Invalid Google token payload'],
                Response::HTTP_UNAUTHORIZED,
            );
        }

        // Find user by Google ID first
        $user = \App\Models\User::findByGoogleId($googleId);

        // If not found by Google ID, check if user exists with same email (link account)
        if (! $user) {
            $user = \App\Models\User::where('email', $email)->first();

            if ($user) {
                // Link existing account with Google
                $user->update([
                    'google_id' => $googleId,
                    'auth_type' => 'google',
                ]);
            } else {
                // Create new user
                $user = \App\Models\User::create([
                    'google_id' => $googleId,
                    'email' => $email,
                    'first_name' => $firstName,
                    'last_name' => $lastName,
                    'google_picture_url' => $pictureUrl,
                    'auth_type' => 'google',
                    'email_verified_at' => now(),
                    'password' => bcrypt(str()->random(32)), // Random password for Google users
                ]);

                // Create user profile
                $user->profile()->create([]);
            }
        }

        // Update picture URL if changed
        if ($pictureUrl && $user->google_picture_url !== $pictureUrl) {
            $user->update(['google_picture_url' => $pictureUrl]);
        }

        // Update last login
        $user->updateLastLogin();

        // Create Sanctum token
        $accessToken = $user->createToken('google-auth');

        return response(
            new AuthResource([
                'user' => $user,
                'access_token' => $accessToken->plainTextToken,
                'expires_at' => null,
            ]),
            Response::HTTP_OK,
        );
    }
}
