import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
import { comparePassword, generateToken } from '@/lib/auth';
import { LoginRequest, AuthResponse } from '@/types/api';
import { RowDataPacket } from 'mysql2';

export async function POST(req: NextRequest) {
    try {
        const body: LoginRequest = await req.json();
        const { email, password, rememberMe } = body;

        // Validation
        if (!email || !password) {
            return NextResponse.json(
                { error: 'E-post och lösenord krävs' },
                { status: 400 }
            );
        }

        // Find user by email or username
        const [users] = await pool.query<RowDataPacket[]>(
            'SELECT * FROM users WHERE email = ? OR username = ?',
            [email, email]
        );

        if (users.length === 0) {
            return NextResponse.json(
                { error: 'Ogiltig e-post/användarnamn eller lösenord' },
                { status: 401 }
            );
        }

        const user = users[0];

        // Verify password (safely handle accounts with no password like Google-only accounts)
        const isValidPassword = user.password_hash ? await comparePassword(password, user.password_hash) : false;

        if (!isValidPassword) {
            return NextResponse.json(
                { error: 'Ogiltig e-post/användarnamn eller lösenord' },
                { status: 401 }
            );
        }

        // Check for email verification
        if (!user.email_verified) {
            return NextResponse.json(
                {
                    error: 'Din e-postadress är inte verifierad än. Vänligen kontrollera din inkorg.',
                    unverified: true,
                    email: user.email
                },
                { status: 403 }
            );
        }

        // Check for 2FA
        if (user.two_factor_enabled) {
            return NextResponse.json({
                twoFactorRequired: true,
                userId: user.id
            });
        }

        // Generate token with variable expiry
        const token = generateToken(
            {
                userId: user.id,
                email: user.email,
                role: user.role,
            },
            rememberMe ? '30d' : '2h'
        );

        return NextResponse.json({
            token,
            user: {
                id: user.id,
                email: user.email,
                username: user.username,
                name: user.full_name || user.username,
                role: user.role,
                created_at: user.created_at,
                email_verified: !!user.email_verified,
                two_factor_enabled: !!user.two_factor_enabled,
                newsletter_subscribed: !!user.newsletter_subscribed,
                personnummer: user.personnummer,
                mobile: user.mobile,
                address: user.address,
                zip_code: user.zip_code,
                city: user.city,
                country: user.country,
                has_password: !!user.password_hash
            }
        });
    } catch (error) {
        console.error('Login error:', error);
        return NextResponse.json(
            { error: 'Internt serverfel' },
            { status: 500 }
        );
    }
}
