"use strict";function validateRequestBody(e){const{secret:t,type:r}=e;if(!t||!r)throw(0,error_1.createError)({statusCode:400,message:"Missing required parameters: 'secret' and 'type'"});const s=["EMAIL","SMS","APP"];if(!s.includes(r))throw(0,error_1.createError)({statusCode:400,message:`Invalid type. Must be one of: ${s.join(", ")}`})}async function saveOrUpdateOTP(e,t,r){const s=await db_1.models.twoFactor.findOne({where:{userId:e}}),a=(0,utils_1.encrypt)(t);return s?await updateTwoFactor(s.id,a,r):await createTwoFactor(e,a,r)}async function updateTwoFactor(e,t,r){try{const[s,[a]]=await db_1.models.twoFactor.update({secret:t,type:r,enabled:!0},{where:{id:e},returning:!0});return a}catch(e){throw(0,error_1.createError)({statusCode:500,message:`Error updating 2FA record: ${e.message}`})}}async function createTwoFactor(e,t,r){try{return await db_1.models.twoFactor.create({userId:e,secret:t,type:r,enabled:!0})}catch(e){throw(0,error_1.createError)({statusCode:500,message:`Error creating 2FA record: ${e.message}`})}}Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;exports.saveOrUpdateOTP=saveOrUpdateOTP;const db_1=require("@b/db"),error_1=require("@b/utils/error"),utils_1=require("./utils");exports.metadata={summary:"Saves the OTP",operationId:"saveOTP",tags:["Auth"],description:"Saves the OTP secret and type for the user",requiresAuth:!0,logModule:"2FA",logTitle:"Save 2FA settings",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{secret:{type:"string",description:"Generated OTP secret"},type:{type:"string",enum:["EMAIL","SMS","APP"],description:"Type of 2FA"}},required:["secret","type"]}}}},responses:{200:{description:"OTP saved successfully",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Success message"}}}}}},400:{description:"Invalid request"},401:{description:"Unauthorized"}}};exports.default=async e=>{const{body:t,user:r,ctx:s}=e;try{null==s||s.step("Validating user authentication");if(!r){null==s||s.fail("User not authenticated");throw(0,error_1.createError)({statusCode:401,message:"Unauthorized"})}null==s||s.step("Validating request data");validateRequestBody(t);null==s||s.step("Saving 2FA configuration");const e=await saveOrUpdateOTP(r.id,t.secret,t.type);null==s||s.success(`2FA settings saved for ${t.type}`);return{message:"OTP saved successfully",otpDetails:e}}catch(e){null==s||s.fail(e.message||"Failed to save OTP");throw e}};