import { NextApiRequest, NextApiResponse } from 'next';
import { UserService } from '../../../../backend/services/userService';
import { generateToken } from '../../../../lib/auth';

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

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

        // Validate input
        if (!username || !password) {
            return res.status(400).json({ success: false, error: 'Username and password are required' });
        }

        // Authenticate user
        const user = await UserService.authenticateUser(username, password);

        if (!user) {
            return res.status(401).json({ success: false, error: 'Invalid username or password' });
        }

        // Check if user is banned
        if (user.status === 'BANNED') {
            return res.status(403).json({ success: false, error: 'Account has been banned' });
        }

        // Generate JWT token
        const token = generateToken(user.id);

        // Set HTTP-only cookie
        res.setHeader('Set-Cookie', `token=${token}; HttpOnly; Path=/; Max-Age=${7 * 24 * 60 * 60}; SameSite=Strict`);

        // Return user data
        return res.status(200).json({
            success: true,
            data: {
                user,
                token // Also return token in body for non-cookie clients
            }
        });
    } catch (error) {
        console.error('Login error:', error);
        return res.status(500).json({ success: false, error: 'Login failed' });
    }
}
