import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
import { hashPassword } from '@/lib/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import crypto from 'crypto';
import { validatePersonnummer, validateAddress, lookupSwedishAddress, validateSwedishMobile } from '@/lib/validation';

export async function POST(req: NextRequest) {
    try {
        const body = await req.json();
        const { email, username, password, name, newsletter, personnummer, mobile, address, zip_code, city, country } = body;

        if (!email || !username || !password || !name || !personnummer || !address || !zip_code || !city) {
            return NextResponse.json(
                { error: 'Alla obligatoriska fält (inklusive adress och personnummer) krävs' },
                { status: 400 }
            );
        }

        // Validate Personnummer (Luhn + Date)
        if (!validatePersonnummer(personnummer)) {
            return NextResponse.json(
                { error: 'Personnummer är ogiltigt. Kontrollera formatet ÅÅÅÅMMDD-XXXX.' },
                { status: 400 }
            );
        }

        // Validate Address Format
        if (!validateAddress(address)) {
            return NextResponse.json(
                { error: 'Ogiltigt adressformat. Ange gatunamn och nummer.' },
                { status: 400 }
            );
        }

        // Verify physical address exists (External API)
        const addressExists = await lookupSwedishAddress(address, zip_code, city);
        if (!addressExists) {
            return NextResponse.json(
                { error: 'Adressen verkar inte existera. Vänligen kontrollera stavning och postnummer.' },
                { status: 400 }
            );
        }

        // Validate Mobile Number
        if (!validateSwedishMobile(mobile)) {
            return NextResponse.json(
                { error: 'Ogiltigt mobilnummer. Ange ett giltigt svenskt mobilnummer.' },
                { status: 400 }
            );
        }

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return NextResponse.json(
                { error: 'Ogiltigt e-postformat' },
                { status: 400 }
            );
        }

        if (username.length < 3) {
            return NextResponse.json(
                { error: 'Användarnamnet måste vara minst 3 tecken långt' },
                { status: 400 }
            );
        }

        if (password.length < 6) {
            return NextResponse.json(
                { error: 'Lösenordet måste vara minst 6 tecken långt' },
                { status: 400 }
            );
        }

        const [existingUsers] = await pool.query<RowDataPacket[]>(
            'SELECT id FROM users WHERE email = ? OR username = ?',
            [email, username]
        );

        if (existingUsers.length > 0) {
            return NextResponse.json(
                { error: 'En användare med denna e-post eller användarnamn finns redan' },
                { status: 409 }
            );
        }

        const [userCount] = await pool.query<RowDataPacket[]>(
            'SELECT COUNT(*) as count FROM users'
        );
        const isFirstUser = userCount[0].count === 0;
        const role = isFirstUser ? 'admin' : 'user';

        const passwordHash = await hashPassword(password);
        const verificationToken = crypto.randomBytes(32).toString('hex');

        const [result] = await pool.query<ResultSetHeader>(
            'INSERT INTO users (email, username, password_hash, full_name, role, newsletter_subscribed, verification_token, personnummer, mobile, address, zip_code, city, country) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [email, username, passwordHash, name, role, newsletter || false, verificationToken, personnummer, mobile, address, zip_code, city, country || 'Sverige']
        );

        const userId = result.insertId;

        const { sendVerificationEmail, sendWelcomeNewsletterEmail } = await import('@/lib/email');
        sendVerificationEmail(email, verificationToken).catch(err => console.error('Failed to send verification email:', err));

        if (newsletter) {
            sendWelcomeNewsletterEmail(email, name).catch(err => console.error('Failed to send newsletter welcome email:', err));
        }

        return NextResponse.json({
            message: 'Registreringen lyckades! Vänligen kontrollera din e-post för att verifiera ditt konto.',
            user: {
                id: userId,
                email,
                name,
                role,
                created_at: new Date(),
                email_verified: false
            }
        }, { status: 201 });
    } catch (error) {
        console.error('Registration error:', error);
        return NextResponse.json(
            { error: 'Internt serverfel' },
            { status: 500 }
        );
    }
}
