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

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

        if (!token || !password) {
            return NextResponse.json({ error: 'Token och nytt lösenord krävs' }, { status: 400 });
        }

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

        // Find user by reset token
        const [users] = await pool.query<RowDataPacket[]>(
            'SELECT id FROM users WHERE verification_token = ?',
            [token]
        );

        if (users.length === 0) {
            return NextResponse.json({ error: 'Ogiltig eller utgången återställningslänk' }, { status: 400 });
        }

        const user = users[0];
        const passwordHash = await hashPassword(password);

        // Update password and clear reset token
        const [result] = await pool.query<ResultSetHeader>(
            'UPDATE users SET password_hash = ?, verification_token = NULL WHERE id = ?',
            [passwordHash, user.id]
        );

        if (result.affectedRows === 0) {
            throw new Error('Kunde inte uppdatera lösenordet');
        }

        return NextResponse.json({
            success: true,
            message: 'Ditt lösenord har ändrats framgångsrikt.'
        });
    } catch (error) {
        console.error('Reset password error:', error);
        return NextResponse.json({ error: 'Internt serverfel' }, { status: 500 });
    }
}
