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

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

        if (!emailOrUsername) {
            return NextResponse.json({ error: 'E-post eller användarnamn krävs' }, { status: 400 });
        }

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

        if (users.length === 0) {
            // Generic success message for security
            return NextResponse.json({
                success: true,
                message: 'Om ett konto finns hos oss har vi skickat en återställningslänk.'
            });
        }

        const user = users[0];
        const resetToken = crypto.randomBytes(32).toString('hex');

        // Store reset token (re-using verification_token field or adding a new column)
        // For simplicity, we'll use verification_token if available or update it.
        // Ideally, a separate password_reset_token table would be better, but let's check init.sql again.
        // init.sql has verification_token. Let's use it or add a column if needed.
        // Actually, let's just use verification_token for now.
        await pool.query(
            'UPDATE users SET verification_token = ? WHERE id = ?',
            [resetToken, user.id]
        );

        const resetUrl = `${process.env.NEXT_PUBLIC_APP_URL}/reset-password/${resetToken}`;

        // Send email
        // Send email
        const { sendPasswordResetEmail } = await import('@/lib/email');
        await sendPasswordResetEmail(user.email, resetToken);

        return NextResponse.json({
            success: true,
            message: 'Om ett konto finns hos oss har vi skickat en återställningslänk.'
        });
    } catch (error) {
        console.error('Forgot password error:', error);
        return NextResponse.json({ error: 'Internt serverfel' }, { status: 500 });
    }
}
