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, email } = req.body;

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

        if (username.length < 3) {
            return res.status(400).json({ success: false, error: 'Username must be at least 3 characters' });
        }

        if (password.length < 6) {
            return res.status(400).json({ success: false, error: 'Password must be at least 6 characters' });
        }

        // Check if username already exists
        const existingUser = await UserService.getUserByUsername(username);
        if (existingUser) {
            return res.status(409).json({ success: false, error: 'Username already taken' });
        }

        // Create new user
        const user = await UserService.createUser(username, password, email);

        // 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 (without password)
        return res.status(201).json({
            success: true,
            data: {
                user: {
                    id: user.id,
                    username: user.username,
                    avatarUrl: user.avatarUrl,
                    role: user.role,
                    status: user.status
                },
                token // Also return token in body for non-cookie clients
            }
        });
    } catch (error) {
        console.error('Registration error:', error);
        return res.status(500).json({ success: false, error: 'Registration failed' });
    }
}
