import { NextResponse } from 'next/server';
import { authenticateToken, AuthenticatedRequest } from '@/lib/middleware';
import pool from '@/lib/db';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { validateSwedishMobile, normalizeSwedishMobile, validatePersonnummer, validateAddress } from '@/lib/validation';

async function getHandler(req: AuthenticatedRequest) {
    try {
        if (!req.user) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const [users] = await pool.query<RowDataPacket[]>(
            'SELECT id, email, username, full_name, role, created_at, personnummer, mobile, address, zip_code, city, country, email_verified, newsletter_subscribed, two_factor_enabled, password_hash FROM users WHERE id = ?',
            [req.user.userId]
        );

        if (users.length === 0) {
            return NextResponse.json({ error: 'User not found' }, { status: 404 });
        }

        const user = users[0];

        return NextResponse.json({
            user: {
                id: user.id,
                email: user.email,
                username: user.username,
                name: user.full_name,
                role: user.role,
                created_at: user.created_at,
                personnummer: user.personnummer,
                mobile: user.mobile,
                address: user.address,
                zip_code: user.zip_code,
                city: user.city,
                country: user.country,
                email_verified: Boolean(user.email_verified),
                newsletter_subscribed: Boolean(user.newsletter_subscribed),
                two_factor_enabled: Boolean(user.two_factor_enabled),
                has_password: !!user.password_hash
            },
        });
    } catch (error) {
        console.error('Get me error:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}

async function patchHandler(req: AuthenticatedRequest) {
    try {
        if (!req.user) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const body = await req.json();
        const { full_name, personnummer, mobile, address, zip_code, city, country } = body;

        // Validation
        if (full_name && full_name.length < 2) {
            return NextResponse.json({ error: 'Namnet är för kort.' }, { status: 400 });
        }

        if (personnummer && !validatePersonnummer(personnummer)) {
            return NextResponse.json({ error: 'Ogiltigt personnummer. Använd formatet YYYYMMDD-XXXX.' }, { status: 400 });
        }

        let normalizedMobile = mobile;
        if (mobile) {
            if (!validateSwedishMobile(mobile)) {
                return NextResponse.json({ error: 'Ogiltigt mobilnummer. Ange ett giltigt svenskt mobilnummer.' }, { status: 400 });
            }
            normalizedMobile = normalizeSwedishMobile(mobile);
        }

        if (address && !validateAddress(address)) {
            return NextResponse.json({ error: 'Ogiltig adress. Ange gatuadress och nummer.' }, { status: 400 });
        }

        const [result] = await pool.query<ResultSetHeader>(
            `UPDATE users SET 
                full_name = COALESCE(?, full_name),
                personnummer = COALESCE(?, personnummer),
                mobile = COALESCE(?, mobile),
                address = COALESCE(?, address),
                zip_code = COALESCE(?, zip_code),
                city = COALESCE(?, city)
            WHERE id = ?`,
            [full_name, personnummer, normalizedMobile, address, zip_code, city, req.user.userId]
        );

        return NextResponse.json({
            success: true,
            message: 'Profilen har uppdaterats.'
        });
    } catch (error) {
        console.error('Update profile error:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}

export const GET = authenticateToken(getHandler);
export const PATCH = authenticateToken(patchHandler);
