"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.metadata = void 0;
const db_1 = require("@b/db");
const error_1 = require("@b/utils/error");
const query_1 = require("@b/utils/query");
const sequelize_1 = require("sequelize");
const console_1 = require("@b/utils/console");
const notification_1 = require("@b/services/notification");
exports.metadata = {
    summary: "Emergency Cancel & Refund ICO (SuperAdmin Only)",
    description: "Emergency cancellation endpoint for SuperAdmins only. Cancels an active ICO offering and refunds ALL investors. Use this for scam prevention or critical security issues.",
    operationId: "emergencyCancelIcoOffering",
    tags: ["ICO", "Admin", "Offerings", "Emergency"],
    parameters: [
        {
            name: "id",
            in: "path",
            description: "ID of the ICO offering to cancel",
            required: true,
            schema: {
                type: "string",
            },
        },
    ],
    requestBody: {
        required: true,
        content: {
            "application/json": {
                schema: {
                    type: "object",
                    properties: {
                        reason: {
                            type: "string",
                            description: "Reason for emergency cancellation (required for audit trail, minimum 10 characters)",
                        },
                    },
                    required: ["reason"],
                },
            },
        },
    },
    requiresAuth: true,
    permission: "manage.system", // SuperAdmin only
    responses: {
        200: {
            description: "ICO cancelled and all investors refunded successfully",
        },
        401: query_1.unauthorizedResponse,
        403: {
            description: "Forbidden - SuperAdmin privileges required",
        },
        404: (0, query_1.notFoundMetadataResponse)("Offering"),
        500: query_1.serverErrorResponse,
    },
    logModule: "ADMIN_ICO",
    logTitle: "Emergency Cancel & Refund ICO",
};
exports.default = async (data) => {
    var _a, _b, _c, _d;
    const { user, params, body, ctx } = data;
    if (!(user === null || user === void 0 ? void 0 : user.id)) {
        throw (0, error_1.createError)({
            statusCode: 401,
            message: "Unauthorized: SuperAdmin privileges required",
        });
    }
    ctx === null || ctx === void 0 ? void 0 : ctx.step("Verifying SuperAdmin privileges");
    // Verify user is SuperAdmin by checking role
    const userWithRole = await db_1.models.user.findByPk(user.id, {
        include: [{
                model: db_1.models.role,
                as: "role",
                attributes: ["name"],
            }],
    });
    if (!userWithRole || ((_a = userWithRole.role) === null || _a === void 0 ? void 0 : _a.name) !== "Super Admin") {
        throw (0, error_1.createError)({
            statusCode: 403,
            message: "Forbidden: This endpoint is restricted to SuperAdmins only",
        });
    }
    const { id } = params;
    const { reason } = body;
    if (!reason || reason.trim().length < 10) {
        throw (0, error_1.createError)({
            statusCode: 400,
            message: "Cancellation reason is required (minimum 10 characters)",
        });
    }
    let transaction;
    try {
        transaction = await db_1.sequelize.transaction();
        ctx === null || ctx === void 0 ? void 0 : ctx.step("Finding ICO offering");
        // Find the offering with details
        const offering = await db_1.models.icoTokenOffering.findByPk(id, {
            transaction,
            include: [{
                    model: db_1.models.user,
                    as: "user",
                    attributes: ["id", "firstName", "lastName", "email"],
                }],
        });
        if (!offering) {
            throw (0, error_1.createError)({ statusCode: 404, message: "ICO offering not found" });
        }
        ctx === null || ctx === void 0 ? void 0 : ctx.step("Retrieving all active investments");
        // Get all transactions (investments) that need refunds
        const transactions = await db_1.models.icoTransaction.findAll({
            where: {
                offeringId: id,
                status: { [sequelize_1.Op.in]: ["PENDING", "VERIFICATION", "RELEASED"] },
            },
            include: [{
                    model: db_1.models.user,
                    as: "user",
                    attributes: ["id", "firstName", "lastName", "email"],
                }],
            transaction,
        });
        console_1.logger.info("ADMIN_ICO_CANCEL", `Found ${transactions.length} active investments to refund`);
        ctx === null || ctx === void 0 ? void 0 : ctx.step(`Processing ${transactions.length} refunds`);
        let totalRefunded = 0;
        let successfulRefunds = 0;
        let failedRefunds = 0;
        const refundDetails = [];
        // Process each investment refund
        for (const investment of transactions) {
            try {
                // Find user's wallet for the purchase currency
                const wallet = await db_1.models.wallet.findOne({
                    where: {
                        userId: investment.userId,
                        type: investment.walletType,
                        currency: investment.purchaseCurrency,
                    },
                    lock: true,
                    transaction,
                });
                if (!wallet) {
                    console_1.logger.error("ADMIN_ICO_CANCEL", `Wallet not found for user ${investment.userId}`);
                    failedRefunds++;
                    refundDetails.push({
                        transactionId: investment.id,
                        userId: investment.userId,
                        amount: investment.amount,
                        currency: investment.purchaseCurrency,
                        status: "FAILED",
                        reason: "Wallet not found",
                    });
                    continue;
                }
                // Refund the amount to user's wallet
                await wallet.update({
                    balance: wallet.balance + investment.amount,
                }, { transaction });
                // Create refund transaction record
                await db_1.models.transaction.create({
                    userId: investment.userId,
                    type: "ICO_REFUND",
                    status: "COMPLETED",
                    amount: investment.amount,
                    fee: 0,
                    currency: investment.purchaseCurrency,
                    description: `Emergency refund for ICO: ${offering.name}. Reason: ${reason}`,
                    referenceId: investment.id,
                }, { transaction });
                // Update investment status to REJECTED with refund note
                await investment.update({
                    status: "REJECTED",
                    rejectReason: `EMERGENCY CANCELLATION - ${reason}`,
                }, { transaction });
                totalRefunded += investment.amount;
                successfulRefunds++;
                refundDetails.push({
                    transactionId: investment.id,
                    userId: investment.userId,
                    userName: investment.user ? `${investment.user.firstName} ${investment.user.lastName}` : "Unknown",
                    amount: investment.amount,
                    currency: investment.purchaseCurrency,
                    status: "SUCCESS",
                });
                console_1.logger.success("ADMIN_ICO_CANCEL", `Refunded ${investment.amount} ${investment.purchaseCurrency} to user ${investment.userId}`);
            }
            catch (refundError) {
                console_1.logger.error("ADMIN_ICO_CANCEL", `Failed to refund investment ${investment.id}`, refundError);
                failedRefunds++;
                refundDetails.push({
                    transactionId: investment.id,
                    userId: investment.userId,
                    amount: investment.amount,
                    currency: investment.purchaseCurrency,
                    status: "FAILED",
                    reason: refundError.message,
                });
            }
        }
        ctx === null || ctx === void 0 ? void 0 : ctx.step("Updating offering status to CANCELLED");
        // Update offering status to CANCELLED
        await offering.update({
            status: "CANCELLED",
            cancelledAt: new Date(),
            cancelledBy: user.id,
            cancellationReason: reason,
        }, { transaction });
        // Log admin activity
        await db_1.models.icoAdminActivity.create({
            userId: user.id,
            offeringId: id,
            action: "EMERGENCY_CANCEL_REFUND",
            details: JSON.stringify({
                reason,
                totalInvestments: transactions.length,
                successfulRefunds,
                failedRefunds,
                totalRefunded,
                refundDetails,
                cancelledBy: (_b = userWithRole.role) === null || _b === void 0 ? void 0 : _b.name,
                timestamp: new Date().toISOString(),
            }),
        }, { transaction });
        // If any refunds failed, rollback the entire transaction for data consistency
        if (failedRefunds > 0) {
            await transaction.rollback();
            throw (0, error_1.createError)({
                statusCode: 500,
                message: `Failed to refund ${failedRefunds} investment(s). Transaction rolled back. Please resolve wallet issues and try again.`,
            });
        }
        await transaction.commit();
        ctx === null || ctx === void 0 ? void 0 : ctx.step("Sending notifications to refunded investors");
        // Send notifications to all refunded investors (non-blocking)
        for (const detail of refundDetails) {
            if (detail.status === "SUCCESS") {
                try {
                    await notification_1.notificationService.send({
                        userId: detail.userId,
                        type: "ICO",
                        channels: ["IN_APP"],
                        idempotencyKey: `ico_refund_${id}_${detail.userId}_${detail.transactionId}`,
                        data: {
                            title: "ICO Investment Refunded",
                            message: `Your investment of ${detail.amount} ${detail.currency} in "${offering.name}" has been refunded due to: ${reason}`,
                        },
                        priority: "HIGH"
                    });
                }
                catch (notifError) {
                    console_1.logger.error("ADMIN_ICO_CANCEL", "Failed to send refund notification", notifError);
                }
            }
        }
        ctx === null || ctx === void 0 ? void 0 : ctx.success("Emergency cancellation and refunds completed successfully");
        return {
            message: "ICO offering cancelled and all investments refunded successfully",
            data: {
                offeringId: id,
                offeringName: offering.name,
                totalInvestments: transactions.length,
                successfulRefunds,
                failedRefunds,
                totalRefunded,
                currency: ((_c = transactions[0]) === null || _c === void 0 ? void 0 : _c.purchaseCurrency) || "N/A",
                cancelledBy: `${userWithRole.firstName} ${userWithRole.lastName}`,
                reason,
                refundDetails,
            },
        };
    }
    catch (error) {
        // Only rollback if transaction exists and hasn't been committed/rolled back
        if (transaction) {
            try {
                if (!transaction.finished) {
                    await transaction.rollback();
                }
            }
            catch (rollbackError) {
                // Ignore rollback errors if transaction is already finished
                if (!((_d = rollbackError.message) === null || _d === void 0 ? void 0 : _d.includes("already been finished"))) {
                    console_1.logger.error("ADMIN_ICO_CANCEL", "Transaction rollback failed", rollbackError);
                }
            }
        }
        console_1.logger.error("ADMIN_ICO_CANCEL", "Error cancelling ICO offering", error);
        // If it's already a createError, rethrow it
        if (error.statusCode) {
            throw error;
        }
        // Otherwise, wrap it in a generic error
        throw (0, error_1.createError)({
            statusCode: 500,
            message: error.message || "Failed to cancel ICO offering and refund investments",
        });
    }
};
