"use strict";
(() => {
var exports = {};
exports.id = 1659;
exports.ids = [1659];
exports.modules = {

/***/ 2261:
/***/ ((module) => {

module.exports = require("serverless-mysql");

/***/ }),

/***/ 4300:
/***/ ((module) => {

module.exports = require("buffer");

/***/ }),

/***/ 2081:
/***/ ((module) => {

module.exports = require("child_process");

/***/ }),

/***/ 6113:
/***/ ((module) => {

module.exports = require("crypto");

/***/ }),

/***/ 7147:
/***/ ((module) => {

module.exports = require("fs");

/***/ }),

/***/ 3685:
/***/ ((module) => {

module.exports = require("http");

/***/ }),

/***/ 1017:
/***/ ((module) => {

module.exports = require("path");

/***/ }),

/***/ 7918:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ handler)
/* harmony export */ });
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2224);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2163);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6825);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_2__);
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ const fs = __webpack_require__(7147);
const path = __webpack_require__(1017);
const { execSync  } = __webpack_require__(2081);



/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * API handler
 * ==============================================================================
 * @type {import("next").NextApiHandler}
 */ async function handler(req, res) {
    /**
     * Check method
     *
     * @description Check request method and return if invalid
     */ if (req.method !== "GET") return res.json({
        msg: "Failed!"
    });
    /**
     * User auth
     *
     * @description Authenticate user
     */ const user = await _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_2___default()(req, res);
    if (!user) {
        return res.json({
            success: false,
            msg: "Unauthorized"
        });
    }
    /**
     * Send Response
     *
     * @description Send a boolean response
     */ try {
        /**
         * Create new user folder and file
         *
         * @description Create new user folder and file
         */ const isProduction = "production".match(/production/);
        /**
         * Create new user folder and file
         *
         * @description Create new user folder and file
         */ const diskUsageDb = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`
            SELECT table_schema, 
            SUM((data_length+index_length)/1024/1024) AS "mb" from 
            information_schema.tables
            where table_schema like ?
            group by table_schema
        `, [
            `datasquirel_user_${user.id}%`
        ]);
        const totalDbDiskUsageInMb = diskUsageDb.reduce((/** @type {any} */ prev, /** @type {any} */ current, /** @type {Number} */ currentIndex)=>{
            if (prev?.mb) {
                return prev.mb + current.mb;
            } else {
                return prev + current.mb;
            }
        }, 0);
        /**
         * Create new user folder and file
         *
         * @description Create new user folder and file
         */ let totalFileUsageInMb = 0;
        const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
        if (!STATIC_ROOT) {
            console.log("Static File ENV not Found!");
            throw new Error("No Static Path!");
        }
        if (!STATIC_ROOT && !fs.existsSync(STATIC_ROOT)) {
            fs.mkdirSync(STATIC_ROOT, {
                recursive: true
            });
        }
        const USER_STATIC_DIR = path.join(STATIC_ROOT, `images/user-images/user-${user.id}`);
        if (!fs.existsSync(USER_STATIC_DIR)) {
            fs.mkdirSync(USER_STATIC_DIR, {
                recursive: true
            });
        }
        const userMediaFilePath = path.join(STATIC_ROOT, `images/user-images/user-${user.id}`);
        const userVideosPath = path.join(STATIC_ROOT, `videos/user-videos/user-${user.id}`);
        if (!fs.existsSync(userVideosPath)) {
            fs.mkdirSync(userVideosPath, {
                recursive: true
            });
        }
        async function readFolders(/** @type {String} */ path) {
            try {
                const userMediaFiles = fs.readdirSync(path);
                for(let i = 0; i < userMediaFiles.length; i++){
                    const file = userMediaFiles[i];
                    const fileFullPath = path + "/" + file;
                    if (!file.match(/\..{3,4}$/)) {
                        await readFolders(fileFullPath);
                        continue;
                    }
                    if (fs.existsSync(fileFullPath)) {
                        const fileSize = fs.statSync(fileFullPath);
                        totalFileUsageInMb += fileSize.size / 1024 / 1024;
                    } else {
                        const isProduction = "production".match(/production/);
                        if (!STATIC_ROOT) {
                            console.log("Static File ENV not Found!");
                            throw new Error("No Static Path!");
                        }
                        const userMediaUrl = fileFullPath.replace(STATIC_ROOT, process.env.DSQL_STATIC_HOST || "");
                        const userMediaPath = fileFullPath.replace(STATIC_ROOT, "");
                        const deleteMedia = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM user_media WHERE media_path = ? OR media_thumbnail_path = ? OR media_url=? OR media_thumbnail_url=?`, [
                            userMediaPath,
                            userMediaPath,
                            userMediaUrl,
                            userMediaUrl, 
                        ]);
                        console.log(`MEDIA => ${userMediaUrl} DELETED FROM DATABASE`);
                    }
                }
            } catch (/** @type {any} */ error) {
                console.log("ERROR in getDiskUsage API route =>", error.message);
                _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
                    component: "/api/getDiskUsage/lines-93-101",
                    message: error.message
                });
            }
        }
        await readFolders(userMediaFilePath);
        await readFolders(userVideosPath);
        const totalUsageInMb = totalFileUsageInMb + totalDbDiskUsageInMb;
        res.json({
            success: true,
            total: totalUsageInMb
        });
    ////////////////////////////////////////
    } catch (/** @type {any} */ error) {
        ////////////////////////////////////////
        _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
            component: "/api/getDiskUsage/main-catch-error",
            message: error.message,
            user: user
        });
        res.json({
            success: false,
            msg: "Disk Usage Calculation Error!"
        });
    ////////////////////////////////////////
    }
}


/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [2224,2163,6825], () => (__webpack_exec__(7918)));
module.exports = __webpack_exports__;

})();