import { NextResponse } from 'next/server';
import { authenticateToken, AuthenticatedRequest } from '@/lib/middleware';
import pool from '@/lib/db';
import { hashPassword, comparePassword } from '@/lib/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

async function handler(req: AuthenticatedRequest) {
    try {
        if (!req.user) {
            return NextResponse.json({ error: 'Obehörig' }, { status: 401 });
        }

        const { currentPassword, newPassword } = await req.json();

        if (!newPassword) {
            return NextResponse.json({ error: 'Nytt lösenord krävs' }, { status: 400 });
        }

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

        // Check current password
        const [users] = await pool.query<RowDataPacket[]>(
            'SELECT password_hash FROM users WHERE id = ?',
            [req.user.userId]
        );

        if (users.length === 0) {
            return NextResponse.json({ error: 'Användaren hittades inte' }, { status: 404 });
        }

        const user = users[0];

        // If user has a password, they must provide the correct current one
        if (user.password_hash) {
            if (!currentPassword) {
                return NextResponse.json({ error: 'Nuvarande lösenord krävs' }, { status: 400 });
            }
            const isValid = await comparePassword(currentPassword, user.password_hash);
            if (!isValid) {
                return NextResponse.json({ error: 'Ditt nuvarande lösenord är felaktigt' }, { status: 400 });
            }
        }

        // Hash and update
        const newHash = await hashPassword(newPassword);
        await pool.query<ResultSetHeader>(
            'UPDATE users SET password_hash = ? WHERE id = ?',
            [newHash, req.user.userId]
        );

        return NextResponse.json({ success: true, message: 'Ditt lösenord har uppdaterats.' });
    } catch (error) {
        console.error('Change password error:', error);
        return NextResponse.json({ error: 'Internt serverfel' }, { status: 500 });
    }
}

export const POST = authenticateToken(handler);
