"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.increaseWalletBalance = exports.resetWalletBalance = exports.addHistoryWalletUser = exports.createWalletDataForUser = exports.getUserWallet = exports.requestCreateWallet = void 0;
const functions = require("firebase-functions");
const collections_1 = require("./collections");
const custom_error_1 = require("./utils/custom_error");
exports.requestCreateWallet = functions.https.onCall(async (data, context) => {
    try {
        // Check if user is authenticated
        if (!context.auth) {
            throw new custom_error_1.CustomError("unauthenticated", "User must be authenticated");
        }
        const userId = context.auth.uid;
        // Check if wallet already exists by trying to get it
        const userWalletRef = collections_1.userWalletCol.doc(userId);
        const userWallet = await userWalletRef.get();
        if (userWallet.exists) {
            return { success: false, message: "User wallet already exists" };
        }
        // Create wallet since it doesn't exist
        await (0, exports.createWalletDataForUser)(userId);
        return { success: true, message: "Wallet created successfully" };
    }
    catch (error) {
        throw error;
    }
});
/**
 * Retrieves a user's wallet information from the database
 * @param userId - The ID of the user whose wallet to retrieve
 * @returns Promise<UserWalletModel> - The user's wallet information
 * @throws CustomError if wallet is not found or on database errors
 */
const getUserWallet = async (userId) => {
    try {
        const walletRef = collections_1.userWalletCol.doc(userId);
        const walletDoc = await walletRef.get();
        if (!walletDoc.exists) {
            throw new custom_error_1.CustomError("not-found", `Wallet not found for user: ${userId}`);
        }
        return walletDoc.data();
    }
    catch (error) {
        if (error instanceof custom_error_1.CustomError) {
            throw error;
        }
        // Cast error to any to safely access message property
        const errorMessage = (error === null || error === void 0 ? void 0 : error.message) || "Unknown error occurred";
        throw new custom_error_1.CustomError("internal", `Error retrieving wallet for user ${userId}: ${errorMessage}`);
    }
};
exports.getUserWallet = getUserWallet;
const createWalletDataForUser = async (userId) => {
    try {
        const userWalletCheckRef = collections_1.userWalletCol.doc(userId);
        const userWalletCheck = await userWalletCheckRef.get();
        if (userWalletCheck.exists) {
            throw new custom_error_1.CustomError("already-exists", "user wallet already exists");
        }
        const newUserWallet = {
            id: userId,
            balance: 0,
            updatedAt: new Date(),
            userId: userId,
        };
        await collections_1.userWalletCol.doc(userId).set(newUserWallet);
    }
    catch (error) {
        throw error;
    }
};
exports.createWalletDataForUser = createWalletDataForUser;
const addHistoryWalletUser = async (walletId, history) => {
    try {
        await (0, collections_1.userWalletHistoryCol)(walletId).add(history);
    }
    catch (error) {
        throw error;
    }
};
exports.addHistoryWalletUser = addHistoryWalletUser;
/**
 * Resets a user's wallet balance to 0
 * @param userId - The ID of the user whose wallet balance to reset
 * @throws CustomError if wallet is not found or on database errors
 */
const resetWalletBalance = async (userId) => {
    try {
        const walletRef = collections_1.userWalletCol.doc(userId);
        const walletDoc = await walletRef.get();
        if (!walletDoc.exists) {
            throw new custom_error_1.CustomError("not-found", `Wallet not found for user: ${userId}`);
        }
        await walletRef.update({
            balance: 0,
            updatedAt: new Date(),
        });
    }
    catch (error) {
        // Cast error to any to safely access message property
        const errorMessage = (error === null || error === void 0 ? void 0 : error.message) || "Unknown error occurred";
        throw new custom_error_1.CustomError("internal", `Error resetting wallet balance for user ${userId}: ${errorMessage}`);
    }
};
exports.resetWalletBalance = resetWalletBalance;
/**
 * Increases a user's wallet balance by the specified amount
 * @param userId - The ID of the user whose wallet balance to increase
 * @param amount - The amount to increase the balance by
 * @throws CustomError if wallet is not found or on database errors
 */
const increaseWalletBalance = async (userId, amount) => {
    var _a;
    try {
        const walletRef = collections_1.userWalletCol.doc(userId);
        const walletDoc = await walletRef.get();
        if (!walletDoc.exists) {
            throw new custom_error_1.CustomError("not-found", `Wallet not found for user: ${userId}`);
        }
        const currentBalance = ((_a = walletDoc.data()) === null || _a === void 0 ? void 0 : _a.balance) || 0;
        const newBalance = currentBalance + amount;
        await walletRef.update({
            balance: newBalance,
            updatedAt: new Date(),
        });
        // Add transaction to wallet history
        await (0, exports.addHistoryWalletUser)(userId, {
            initialAmount: currentBalance,
            finalAmount: newBalance,
            transactionAmount: amount,
            createdAt: new Date(),
            userId: userId,
            status: "success",
            description: "Consultation payment received",
            type: "Payment",
        });
    }
    catch (error) {
        const errorMessage = (error === null || error === void 0 ? void 0 : error.message) || "Unknown error occurred";
        throw new custom_error_1.CustomError("internal", `Error increasing wallet balance for user ${userId}: ${errorMessage}`);
    }
};
exports.increaseWalletBalance = increaseWalletBalance;
//# sourceMappingURL=user-wallet-functions.js.map