import { NextRequest, NextResponse } from 'next/server';
import { getGoogleUser } from '@/lib/google-auth';
import pool from '@/lib/db';
import { generateToken } from '@/lib/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export async function GET(req: NextRequest) {
    const searchParams = req.nextUrl.searchParams;
    const code = searchParams.get('code');

    if (!code) {
        return NextResponse.redirect(new URL('/login?error=GoogleAuthFailed', req.url));
    }

    try {
        const googleUser = await getGoogleUser(code);
        const { email, name, sub: googleId } = googleUser;

        // Check if user exists
        const [users] = await pool.query<RowDataPacket[]>(
            'SELECT * FROM users WHERE email = ?',
            [email]
        );

        let user;
        if (users.length > 0) {
            user = users[0];
            // Update google_id if not set
            if (!user.google_id) {
                await pool.query('UPDATE users SET google_id = ?, email_verified = 1 WHERE id = ?', [googleId, user.id]);
            }
        } else {
            // Create new user
            const username = email.split('@')[0] + Math.random().toString(36).substring(7);

            const [result] = await pool.query<ResultSetHeader>(
                `INSERT INTO users (email, username, full_name, google_id, email_verified, role) 
                 VALUES (?, ?, ?, ?, 1, 'user')`,
                [email, username, name, googleId]
            );

            const [newUsers] = await pool.query<RowDataPacket[]>(
                'SELECT * FROM users WHERE id = ?',
                [result.insertId]
            );
            user = newUsers[0];
        }

        // Generate token
        const token = generateToken({
            userId: user.id,
            email: user.email,
            role: user.role,
        }, '7d'); // Long expiry for OAuth usually fine, or check rememberMe logic

        // Redirect to a handling page on the frontend
        const redirectUrl = new URL('/login', req.url);
        redirectUrl.searchParams.set('token', token);

        // Only pass essential auth data in the URL to protect PII
        // Full profile data will be fetched securely by the frontend via /api/auth/me
        const safeUser = {
            id: user.id,
            email: user.email,
            username: user.username,
            name: user.full_name || user.username,
            role: user.role,
            has_password: !!user.password_hash
        };

        redirectUrl.searchParams.set('user', JSON.stringify(safeUser));

        return NextResponse.redirect(redirectUrl);
    } catch (error) {
        console.error('Google Auth Callback Error:', error);
        return NextResponse.redirect(new URL('/login?error=GoogleAuthFailed', req.url));
    }
}
