"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const error_1=require("@b/utils/error"),db_1=require("@b/db"),token_1=require("@b/utils/token"),utils_1=require("../utils"),emails_1=require("@b/utils/emails");exports.metadata={summary:"Check account deletion code and delete user",operationId:"checkAccountDeletionCode",tags:["Account"],description:"Checks the deletion code, deletes the user's account if valid, and sends a confirmation email.",requiresAuth:!1,logModule:"ACCOUNT",logTitle:"Confirm account deletion",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",format:"email",description:"Email of the user confirming account deletion"},token:{type:"string",description:"Account deletion confirmation token"}},required:["email","token"]}}}},responses:{200:{description:"User account deleted successfully",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Success message"}}}}}},400:{description:"Invalid request or token",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message"}}}}}}}};exports.default=async e=>{const{body:t,ctx:r}=e,{email:o,token:i}=t;try{null==r||r.step("Validating account deletion confirmation");if(!o||!i){null==r||r.fail("Email and token are required");throw(0,error_1.createError)({statusCode:400,message:"Email and token are required"})}null==r||r.step(`Looking up user: ${o}`);const e=await db_1.models.user.findOne({where:{email:o}});if(!e){null==r||r.fail("User not found");throw(0,error_1.createError)({message:"User not found",statusCode:404})}null==r||r.step("Verifying deletion token");const t=await(0,token_1.verifyResetToken)(i);if(!t){null==r||r.fail("Invalid or expired token");throw(0,error_1.createError)({message:"Invalid or expired token",statusCode:400})}null==r||r.step("Checking token usage");try{if(t.jti!==await(0,utils_1.addOneTimeToken)(t.jti,new Date)){null==r||r.fail("Token already used");throw(0,error_1.createError)({statusCode:500,message:"Token has already been used"})}}catch(e){null==r||r.fail("Token validation failed");throw(0,error_1.createError)({statusCode:500,message:"Token has already been used"})}null==r||r.step("Deleting user account");await db_1.models.user.destroy({where:{id:e.id}});try{null==r||r.step("Sending deletion confirmation email");await emails_1.emailQueue.add({emailData:{TO:e.email,FIRSTNAME:e.firstName},emailType:"AccountDeletionConfirmed"});null==r||r.success(`User account ${o} deleted successfully`);return{message:"User account deleted successfully"}}catch(e){null==r||r.fail("Failed to send deletion confirmation email");throw(0,error_1.createError)({message:e.message,statusCode:500})}}catch(e){null==r||r.fail(e.message||"Account deletion confirmation failed");throw e}};