"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");
exports.metadata = {
    summary: "Fetch Token Release Transactions",
    description: "Retrieves token release transactions for a given token (offering) ID, optionally filtered by status and paginated with sorting support.",
    operationId: "getTokenReleaseTransactions",
    tags: ["ICO", "Token", "Release"],
    logModule: "ICO",
    logTitle: "Get Token Releases",
    requiresAuth: true,
    parameters: [
        {
            index: 0,
            name: "id",
            in: "param",
            required: true,
            schema: { type: "string" },
            description: "Token (offering) ID",
        },
        {
            index: 1,
            name: "status",
            in: "query",
            required: false,
            schema: { type: "string" },
            description: "Filter transactions by status (PENDING, VERIFICATION, RELEASED)",
        },
        {
            index: 2,
            name: "page",
            in: "query",
            required: false,
            schema: { type: "number" },
            description: "Page number",
        },
        {
            index: 3,
            name: "limit",
            in: "query",
            required: false,
            schema: { type: "number" },
            description: "Number of items per page",
        },
        {
            index: 4,
            name: "sortField",
            in: "query",
            required: false,
            schema: { type: "string" },
            description: "Field to sort by (default is createdAt). For associated models use dot notation (e.g., 'user.firstName')",
        },
        {
            index: 5,
            name: "sortDirection",
            in: "query",
            required: false,
            schema: { type: "string" },
            description: "Sort direction: asc or desc (default is desc)",
        },
    ],
    responses: {
        200: {
            description: "Token release transactions retrieved successfully.",
            content: {
                "application/json": {
                    schema: {
                        type: "object",
                        properties: {
                            items: {
                                type: "array",
                                items: { type: "object" },
                            },
                            pagination: {
                                type: "object",
                                properties: {
                                    currentPage: { type: "number" },
                                    totalPages: { type: "number" },
                                    totalItems: { type: "number" },
                                    itemsPerPage: { type: "number" },
                                },
                            },
                        },
                    },
                },
            },
        },
        400: { description: "Bad Request" },
        401: { description: "Unauthorized" },
        500: { description: "Internal Server Error" },
    },
};
exports.default = async (data) => {
    const { user, query, params, ctx } = data;
    if (!(user === null || user === void 0 ? void 0 : user.id)) {
        throw (0, error_1.createError)({ statusCode: 401, message: "Unauthorized" });
    }
    ctx === null || ctx === void 0 ? void 0 : ctx.step("Fetching token releases");
    const { id } = params;
    if (!id) {
        throw (0, error_1.createError)({ statusCode: 400, message: "id is required" });
    }
    const where = { offeringId: id };
    if (query.status) {
        where.status = query.status.toUpperCase();
    }
    const page = parseInt(query.page, 10) || 1;
    const limit = parseInt(query.limit, 10) || 10;
    const offset = (page - 1) * limit;
    const rawSortField = query.sortField || "createdAt";
    const sortDirection = query.sortDirection && query.sortDirection.toUpperCase() === "ASC"
        ? "ASC"
        : "DESC";
    let orderCriteria;
    if (rawSortField.includes(".")) {
        const parts = rawSortField.split(".");
        if (parts[0] === "user") {
            orderCriteria = [
                [{ model: db_1.models.user, as: "user" }, parts[1], sortDirection],
            ];
        }
        else {
            orderCriteria = [[rawSortField, sortDirection]];
        }
    }
    else {
        orderCriteria = [[rawSortField, sortDirection]];
    }
    const totalItems = await db_1.models.icoTransaction.count({ where });
    const transactions = await db_1.models.icoTransaction.findAll({
        where,
        include: [
            {
                model: db_1.models.user,
                as: "user",
                attributes: ["firstName", "lastName", "avatar"],
            },
        ],
        offset,
        limit,
        order: orderCriteria,
    });
    const totalPages = Math.ceil(totalItems / limit);
    ctx === null || ctx === void 0 ? void 0 : ctx.success("Get Token Releases retrieved successfully");
    return {
        items: transactions,
        pagination: {
            currentPage: page,
            totalPages,
            totalItems,
            itemsPerPage: limit,
        },
    };
};
