import { NextApiResponse } from 'next';
import { AuthenticatedRequest, requireAuth } from '../../../../lib/middleware/authMiddleware';
import { UserService } from '../../../../backend/services/userService';

export default async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
    if (req.method !== 'PATCH') {
        return res.status(405).json({ success: false, error: 'Method not allowed' });
    }

    // Require authentication
    const isAuthenticated = await requireAuth(req, res);
    if (!isAuthenticated) {
        return;
    }

    try {
        const { username, avatarUrl } = req.body;

        // Update user
        const updatedUser = await UserService.updateUser(req.user!.id, {
            username,
            avatarUrl
        });

        return res.status(200).json({ success: true, data: updatedUser });
    } catch (error) {
        console.error('Error updating user:', error);
        return res.status(500).json({ success: false, error: 'Failed to update user' });
    }
}
