"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const error_1=require("@b/utils/error"),fs_1=require("fs"),path_1=__importDefault(require("path")),mysqldump_1=__importDefault(require("mysqldump")),date_fns_1=require("date-fns");exports.metadata={summary:"Backs up the database",description:"Creates a backup of the entire database",operationId:"backupDatabase",tags:["Admin","Database"],requiresAuth:!0,responses:{200:{description:"Database backup created successfully",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Success message"},backupFile:{type:"string",description:"Path to the backup file"}}}}}},500:{description:"Internal server error"}},permission:"access.database",logModule:"ADMIN_SYS",logTitle:"Database backup"};const checkEnvVariables=()=>{["DB_HOST","DB_USER","DB_NAME"].forEach(e=>{if(!process.env[e])throw(0,error_1.createError)({statusCode:500,message:`Environment variable ${e} is not set`})})},getDbConnection=()=>{const{DB_HOST:e,DB_USER:a,DB_PASSWORD:t,DB_NAME:s}=process.env;if(!e||!a||!s)throw(0,error_1.createError)({statusCode:500,message:"Database configuration is incomplete"});return{host:e,user:a,password:t||"",database:s}};exports.default=async e=>{const{ctx:a}=e;try{null==a||a.step("Validating database configuration");checkEnvVariables();const e=getDbConnection(),t=path_1.default.resolve(process.cwd(),"backup"),s=`${(0,date_fns_1.format)(new Date,"yyyy_MM_dd_HH_mm_ss")}.sql`,r=path_1.default.resolve(t,s);null==a||a.step("Creating backup directory");await fs_1.promises.mkdir(t,{recursive:!0});null==a||a.step("Dumping database to file");await(0,mysqldump_1.default)({connection:e,dumpToFile:r});null==a||a.success(`Database backup created: ${s}`);return{message:"Database backup created successfully"}}catch(e){null==a||a.fail(`Database backup failed: ${e.message}`);throw(0,error_1.createError)({statusCode:500,message:e.message})}};