"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const AuthMiddleware_1 = require("../../Application/Services/AuthMiddleware");
const DIContainer_1 = require("../../Application/Services/DIContainer");
const ErrorResponseService_1 = require("../../Application/Services/ErrorResponseService");
const ValidationMiddleware_1 = require("../../Application/Services/ValidationMiddleware");
const Generalsearch_1 = require("../../Application/Search/Generalsearch");
const Logger_1 = require("../../Application/Services/Logger");
const userRouter = (0, express_1.Router)();
// Create search service that isn't in the container yet
const searchService = new Generalsearch_1.GeneralSearchService(DIContainer_1.container.userRepository, DIContainer_1.container.organizationRepository, DIContainer_1.container.deckRepository);
// Login endpoint
userRouter.post('/login', ValidationMiddleware_1.ValidationMiddleware.combine([
    ValidationMiddleware_1.ValidationMiddleware.validateRequiredFields(['username', 'password']),
    ValidationMiddleware_1.ValidationMiddleware.validateStringLength({
        username: { min: 3, max: 50 },
        password: { min: 6, max: 100 }
    })
]), async (req, res) => {
    try {
        (0, Logger_1.logRequest)('Login endpoint accessed', req, res, { username: req.body.username });
        const { username, password } = req.body;
        const result = await DIContainer_1.container.loginCommandHandler.execute({ username, password });
        if (result) {
            (0, Logger_1.logAuth)('User login successful', result.user.id, { username: result.user.username }, req, res);
            res.json(result);
        }
        else {
            return ErrorResponseService_1.ErrorResponseService.sendUnauthorized(res, 'Invalid username or password');
        }
    }
    catch (error) {
        (0, Logger_1.logError)('Login endpoint error', error, req, res);
        if (error instanceof Error) {
            if (error.message.includes('Invalid username')) {
                return ErrorResponseService_1.ErrorResponseService.sendUnauthorized(res, 'Invalid username or password');
            }
            if (error.message.includes('Invalid password')) {
                return ErrorResponseService_1.ErrorResponseService.sendUnauthorized(res, 'Invalid username or password');
            }
            if (error.message.includes('not verified')) {
                return ErrorResponseService_1.ErrorResponseService.sendUnauthorized(res, 'Please verify your email address');
            }
            if (error.message.includes('deactivated')) {
                return ErrorResponseService_1.ErrorResponseService.sendUnauthorized(res, 'Account has been deactivated');
            }
        }
        return ErrorResponseService_1.ErrorResponseService.sendInternalServerError(res);
    }
});
// Create user endpoint  
userRouter.post('/create', ValidationMiddleware_1.ValidationMiddleware.combine([
    ValidationMiddleware_1.ValidationMiddleware.validateRequiredFields(['username', 'email', 'password']),
    ValidationMiddleware_1.ValidationMiddleware.validateEmailFormat(['email']),
    ValidationMiddleware_1.ValidationMiddleware.validateStringLength({
        username: { min: 3, max: 50 },
        password: { min: 6, max: 100 }
    })
]), async (req, res) => {
    try {
        (0, Logger_1.logRequest)('Create user endpoint accessed', req, res, {
            username: req.body.username,
            email: req.body.email
        });
        const result = await DIContainer_1.container.createUserCommandHandler.execute(req.body);
        (0, Logger_1.logRequest)('User created successfully', req, res, {
            userId: result.id,
            username: result.username
        });
        res.status(201).json(result);
    }
    catch (error) {
        (0, Logger_1.logError)('Create user endpoint error', error, req, res);
        if (error instanceof Error) {
            if (error.message.includes('already exists')) {
                return ErrorResponseService_1.ErrorResponseService.sendConflict(res, error.message);
            }
            if (error.message.includes('validation')) {
                return ErrorResponseService_1.ErrorResponseService.sendBadRequest(res, error.message);
            }
        }
        return ErrorResponseService_1.ErrorResponseService.sendInternalServerError(res);
    }
});
// Get user profile (current user)
userRouter.get('/profile', AuthMiddleware_1.authRequired, async (req, res) => {
    try {
        const userId = req.user.userId;
        (0, Logger_1.logRequest)('Get user profile endpoint accessed', req, res, { userId });
        const result = await DIContainer_1.container.getUserByIdQueryHandler.execute({ id: userId });
        if (!result) {
            (0, Logger_1.logWarning)('User profile not found', { userId }, req, res);
            return ErrorResponseService_1.ErrorResponseService.sendNotFound(res, 'User not found');
        }
        (0, Logger_1.logRequest)('User profile retrieved successfully', req, res, {
            userId,
            username: result.username
        });
        res.json(result);
    }
    catch (error) {
        (0, Logger_1.logError)('Get user profile endpoint error', error, req, res);
        return ErrorResponseService_1.ErrorResponseService.sendInternalServerError(res);
    }
});
// Update user profile (current user)
userRouter.patch('/profile', AuthMiddleware_1.authRequired, async (req, res) => {
    try {
        const userId = req.user.userId;
        (0, Logger_1.logRequest)('Update user profile endpoint accessed', req, res, {
            userId,
            fieldsToUpdate: Object.keys(req.body)
        });
        const result = await DIContainer_1.container.updateUserCommandHandler.execute({ id: userId, ...req.body });
        if (!result) {
            return ErrorResponseService_1.ErrorResponseService.sendNotFound(res, 'User not found');
        }
        (0, Logger_1.logRequest)('User profile updated successfully', req, res, {
            userId,
            username: result.username
        });
        res.json(result);
    }
    catch (error) {
        (0, Logger_1.logError)('Update user profile endpoint error', error, req, res);
        if (error instanceof Error) {
            if (error.message.includes('already exists')) {
                return ErrorResponseService_1.ErrorResponseService.sendConflict(res, error.message);
            }
            if (error.message.includes('validation')) {
                return ErrorResponseService_1.ErrorResponseService.sendBadRequest(res, error.message);
            }
        }
        return ErrorResponseService_1.ErrorResponseService.sendInternalServerError(res);
    }
});
exports.default = userRouter;
//# sourceMappingURL=userRouter.js.map