"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BoardsController = void 0;
const logger_1 = __importDefault(require("../../../logger"));
const activityLogService_1 = require("../../services/activityLogService");
const boardsService_1 = require("../../services/boards/boardsService");
const callControlPlaneApi_1 = require("../../../util/callContolPlane/callControlPlaneApi");
const createBoard = async (req, res) => {
    try {
        const { name, description, applicationId, projectId, orgId } = req.body;
        const { userId } = (0, activityLogService_1.getUserInfo)(req);
        if (!name || !projectId || !orgId) {
            res.status(400).json({
                success: false,
                message: 'name, projectId, and orgId are required',
            });
            return;
        }
        const board = await boardsService_1.boardsService.create({
            name,
            description,
            applicationId,
            projectId,
            workspaceId: orgId,
            createdBy: userId,
        });
        res.status(201).json({
            success: true,
            data: board,
        });
    }
    catch (error) {
        logger_1.default.error(`Error creating board: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to create board',
        });
    }
};
const getBoardList = async (req, res) => {
    try {
        const { projectId, orgId, includeArchived, page, limit } = req.query;
        const { userId } = (0, activityLogService_1.getUserInfo)(req);
        if (!projectId || !orgId) {
            res.status(400).json({
                success: false,
                message: 'projectId and orgId are required',
            });
            return;
        }
        const result = await boardsService_1.boardsService.getList({
            projectId: projectId,
            workspaceId: orgId,
            userId,
            includeArchived: includeArchived === 'true',
            page: page ? Number(page) : undefined,
            limit: limit ? Number(limit) : undefined,
        });
        res.json({
            success: true,
            data: {
                boards: result.boards,
                pagination: {
                    total: result.total,
                    page: result.page,
                    limit: result.limit,
                    totalPages: Math.ceil(result.total / result.limit),
                },
            },
        });
    }
    catch (error) {
        logger_1.default.error(`Error fetching boards: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch boards',
        });
    }
};
const getBoardById = async (req, res) => {
    try {
        const { boardId } = req.params;
        const { projectId, orgId } = req.query;
        const { userId } = (0, activityLogService_1.getUserInfo)(req);
        if (!boardId || !projectId || !orgId) {
            res.status(400).json({
                success: false,
                message: 'boardId, projectId, and orgId are required',
            });
            return;
        }
        const board = await boardsService_1.boardsService.getById(boardId, projectId, orgId);
        if (!board) {
            res.status(404).json({
                success: false,
                message: 'Board not found',
            });
            return;
        }
        const isMember = await boardsService_1.boardsService.isUserMemberOfBoard(boardId, userId);
        if (!isMember) {
            res.status(403).json({
                success: false,
                message: 'Unauthorized: you are not a member of this board',
            });
            return;
        }
        res.json({
            success: true,
            data: board,
        });
    }
    catch (error) {
        logger_1.default.error(`Error fetching board: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch board',
        });
    }
};
const getWidgetCategories = async (req, res) => {
    try {
        const categories = await boardsService_1.boardsService.getWidgetCategories();
        res.json({
            success: true,
            data: categories,
        });
    }
    catch (error) {
        logger_1.default.error(`Error fetching widget categories: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch widget categories',
        });
    }
};
const getWidgetsByCategory = async (req, res) => {
    try {
        const { categoryId } = req.params;
        const { projectId, orgId, applicationId } = req.query;
        if (!categoryId) {
            res.status(400).json({
                success: false,
                message: 'categoryId is required',
            });
            return;
        }
        const widgets = await boardsService_1.boardsService.getWidgetsByCategory(categoryId, applicationId, projectId, orgId);
        res.json({
            success: true,
            data: widgets,
        });
    }
    catch (error) {
        logger_1.default.error(`Error fetching widgets by category: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch widgets',
        });
    }
};
const saveBoard = async (req, res) => {
    try {
        const { boardId } = req.params;
        const projectId = (req.query.projectId ?? req.body?.projectId);
        const orgId = (req.query.orgId ?? req.body?.orgId);
        const { widgets } = req.body ?? {};
        const { userId } = (0, activityLogService_1.getUserInfo)(req);
        if (!boardId || !projectId || !orgId) {
            res.status(400).json({
                success: false,
                message: 'boardId, projectId, and orgId are required',
            });
            return;
        }
        if (!Array.isArray(widgets)) {
            res.status(400).json({
                success: false,
                message: 'body.widgets must be an array',
            });
            return;
        }
        const ok = await boardsService_1.boardsService.saveBoardWidgets(boardId, projectId, orgId, userId, widgets);
        if (!ok) {
            res.status(403).json({
                success: false,
                message: 'Unauthorized or board not found',
            });
            return;
        }
        res.json({
            success: true,
            message: 'Board saved successfully',
        });
    }
    catch (error) {
        logger_1.default.error(`Error saving board: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to save board',
        });
    }
};
const deleteBoard = async (req, res) => {
    try {
        const { boardId } = req.params;
        const projectId = (req.query.projectId ?? req.body?.projectId);
        const orgId = (req.query.orgId ?? req.body?.orgId);
        const { userId } = (0, activityLogService_1.getUserInfo)(req);
        if (!boardId || !projectId || !orgId) {
            res.status(400).json({
                success: false,
                message: 'boardId, projectId, and orgId are required',
            });
            return;
        }
        const isMember = await boardsService_1.boardsService.isUserMemberOfBoard(boardId, userId);
        if (!isMember) {
            res.status(403).json({
                success: false,
                message: 'Unauthorized: you are not a member of this board',
            });
            return;
        }
        const updated = await boardsService_1.boardsService.archive(boardId, projectId, orgId, userId);
        if (!updated) {
            res.status(404).json({
                success: false,
                message: 'Board not found',
            });
            return;
        }
        res.json({
            success: true,
            message: 'Board archived successfully',
        });
    }
    catch (error) {
        logger_1.default.error(`Error archiving board: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to archive board',
        });
    }
};
const getBoardMembers = async (req, res) => {
    try {
        const { boardId } = req.params;
        const projectId = req.query.projectId;
        const orgId = req.query.orgId;
        const { userId } = (0, activityLogService_1.getUserInfo)(req);
        if (!boardId || !projectId || !orgId) {
            res.status(400).json({
                success: false,
                message: 'boardId, projectId, and orgId are required',
            });
            return;
        }
        const members = await boardsService_1.boardsService.getBoardMembers(boardId, projectId, orgId, userId);
        res.json({
            success: true,
            data: { members },
        });
    }
    catch (error) {
        logger_1.default.error(`Error fetching board members: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch board members',
        });
    }
};
const addMembership = async (req, res) => {
    try {
        const { boardId } = req.params;
        const projectId = (req.query.projectId ?? req.body?.projectId);
        const orgId = (req.query.orgId ?? req.body?.orgId);
        const { members } = req.body ?? {};
        const { userId } = (0, activityLogService_1.getUserInfo)(req);
        if (!boardId || !projectId || !orgId) {
            res.status(400).json({
                success: false,
                message: 'boardId, projectId, and orgId are required',
            });
            return;
        }
        if (!Array.isArray(members) || members.length === 0) {
            res.status(400).json({
                success: false,
                message: 'body.members must be a non-empty array of { userId, email }',
            });
            return;
        }
        const validMembers = members
            .filter((m) => m && typeof m.userId === 'string' && typeof m.email === 'string')
            .map((m) => ({ userId: String(m.userId).trim(), email: String(m.email).trim() }))
            .filter((m) => m.userId && m.email);
        if (validMembers.length === 0) {
            res.status(400).json({
                success: false,
                message: 'body.members must contain at least one { userId, email }',
            });
            return;
        }
        const result = await boardsService_1.boardsService.addMembership(boardId, projectId, orgId, userId, validMembers);
        if (result.added === 0 && result.boardName === null) {
            res.status(403).json({
                success: false,
                message: 'Unauthorized or board not found',
            });
            return;
        }
        const userEmails = validMembers.map((m) => m.email);
        if (result.added > 0 && result.boardName && userEmails.length > 0) {
            try {
                await (0, callControlPlaneApi_1.callControlPlane)(`/trusys-emails/board-invite`, {
                    method: 'POST',
                    params: {
                        userEmails,
                        orgId,
                        boardName: result.boardName,
                        boardId,
                        projectId,
                    },
                }, '');
            }
            catch (emailError) {
                logger_1.default.error(`Board invite email failed for board ${boardId}: ${String(emailError?.message ?? emailError)}`);
                // do not fail the request; membership was already added
            }
        }
        res.status(201).json({
            success: true,
            data: { added: result.added },
            message: `Added ${result.added} member(s) to the board`,
        });
    }
    catch (error) {
        logger_1.default.error(`Error adding board membership: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to add board membership',
        });
    }
};
const removeMembership = async (req, res) => {
    try {
        const { boardId } = req.params;
        const projectId = (req.query.projectId ?? req.body?.projectId);
        const orgId = (req.query.orgId ?? req.body?.orgId);
        const { userId: removedUserId } = req.body ?? {};
        const { userId } = (0, activityLogService_1.getUserInfo)(req);
        if (!boardId || !projectId || !orgId) {
            res.status(400).json({
                success: false,
                message: 'boardId, projectId, and orgId are required',
            });
            return;
        }
        if (!removedUserId || typeof removedUserId !== 'string') {
            res.status(400).json({
                success: false,
                message: 'body.userId is required (user to remove)',
            });
            return;
        }
        const ok = await boardsService_1.boardsService.removeMembership(boardId, projectId, orgId, userId, String(removedUserId).trim());
        if (!ok) {
            res.status(403).json({
                success: false,
                message: 'Unauthorized or board not found',
            });
            return;
        }
        res.json({
            success: true,
            message: 'Member removed from board',
        });
    }
    catch (error) {
        logger_1.default.error(`Error removing board membership: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to remove board membership',
        });
    }
};
exports.BoardsController = {
    createBoard,
    getBoardList,
    getBoardById,
    getWidgetCategories,
    getWidgetsByCategory,
    saveBoard,
    deleteBoard,
    getBoardMembers,
    addMembership,
    removeMembership,
};
//# sourceMappingURL=index.js.map