const nocodbService = require('../services/nocodb');
const logger = require('../utils/logger');
const config = require('../config');
const { sanitizeUser, extractId } = require('../utils/helpers');

class UsersController {
    async getAll(req, res) {
        try {
            if (!config.nocodb.loginSheetId) {
                return res.status(500).json({
                    success: false,
                    error: 'Login sheet not configured'
                });
            }
            
            const response = await nocodbService.getAll(config.nocodb.loginSheetId, {
                limit: 100,
                sort: '-created_at'
            });
            
            const users = response.list || [];
            
            // Remove password field from response for security
            const safeUsers = users.map(sanitizeUser);
            
            res.json({
                success: true,
                users: safeUsers
            });
            
        } catch (error) {
            logger.error('Error fetching users:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to fetch users'
            });
        }
    }
    
    async create(req, res) {
        try {
            const { email, password, name, admin } = req.body;
            
            if (!email || !password) {
                return res.status(400).json({
                    success: false,
                    error: 'Email and password are required'
                });
            }
            
            if (!config.nocodb.loginSheetId) {
                return res.status(500).json({
                    success: false,
                    error: 'Login sheet not configured'
                });
            }
            
            // Check if user already exists
            const existingUser = await nocodbService.getUserByEmail(email);
            
            if (existingUser) {
                return res.status(400).json({
                    success: false,
                    error: 'User with this email already exists'
                });
            }
            
            // Create new user
            const userData = {
                Email: email,
                email: email,
                Password: password,
                password: password,
                Name: name || '',
                name: name || '',
                Admin: admin === true,
                admin: admin === true,
                'Created At': new Date().toISOString(),
                created_at: new Date().toISOString()
            };
            
            const response = await nocodbService.create(
                config.nocodb.loginSheetId,
                userData
            );
            
            res.status(201).json({
                success: true,
                message: 'User created successfully',
                user: {
                    id: extractId(response),
                    email: email,
                    name: name,
                    admin: admin
                }
            });
            
        } catch (error) {
            logger.error('Error creating user:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to create user'
            });
        }
    }
    
    async delete(req, res) {
        try {
            const userId = req.params.id;
            
            if (!config.nocodb.loginSheetId) {
                return res.status(500).json({
                    success: false,
                    error: 'Login sheet not configured'
                });
            }
            
            // Don't allow admins to delete themselves
            if (userId === req.session.userId) {
                return res.status(400).json({
                    success: false,
                    error: 'Cannot delete your own account'
                });
            }
            
            await nocodbService.delete(
                config.nocodb.loginSheetId,
                userId
            );
            
            res.json({
                success: true,
                message: 'User deleted successfully'
            });
            
        } catch (error) {
            logger.error('Error deleting user:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to delete user'
            });
        }
    }
}

module.exports = new UsersController();