import crypto from 'node:crypto';
import axios from 'axios';
import env from '#start/env';
import User from '#models/user';
import logger from '@adonisjs/core/services/logger';
export class SumsubService {
    static async generateAccessToken(userId, levelNm) {
        const appToken = env.get('SUMSUB_APP_TOKEN').trim();
        const secretKey = env.get('SUMSUB_SECRET_KEY').trim();
        const levelName = levelNm;
        const externalUserId = `user_${userId}`;
        const timestamp = Math.floor(Date.now() / 1000);
        const method = 'POST';
        const url = '/resources/accessTokens/sdk';
        const bodyObj = {
            userId: externalUserId,
            levelName: levelName,
            ttlInSecs: 600,
        };
        const jsonBody = JSON.stringify(bodyObj);
        const signature = crypto.createHmac('sha256', secretKey);
        signature.update(timestamp + method + url + jsonBody);
        const response = await axios({
            method: 'POST',
            url: `https://api.sumsub.com${url}`,
            data: jsonBody,
            headers: {
                'X-App-Token': appToken,
                'X-App-Access-Sig': signature.digest('hex'),
                'X-App-Access-Ts': timestamp,
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        });
        return response.data.token;
    }
    static async handleWebhook(payload) {
        const { type, applicantId, externalUserId, reviewResult } = payload;
        logger.info(`Received Sumsub Webhook [${type}] for user: ${externalUserId}`);
        if (!externalUserId || !externalUserId.startsWith('user_')) {
            logger.warn(`Sumsub Webhook received with invalid externalUserId format: ${externalUserId}`);
            return;
        }
        const userId = Number.parseInt(externalUserId.replace('user_', ''), 10);
        const user = await User.find(userId);
        if (!user) {
            logger.error(`User with ID ${userId} not found for Sumsub webhook applicant ${applicantId}`);
            return;
        }
        let profile = null;
        if (user.accountType === 'individual') {
            profile = await user.related('individualProfile').query().first();
        }
        else if (user.accountType === 'business') {
            profile = await user.related('businessProfile').query().first();
        }
        if (!profile) {
            logger.error(`Profile not found for User ID ${userId} with accountType ${user.accountType}`);
            return;
        }
        const complianceAssessment = await user.related('complianceAssessment').query().first();
        if (type === 'applicantReviewed') {
            const reviewAnswer = reviewResult?.reviewAnswer;
            if (reviewAnswer === 'GREEN') {
                logger.info(`KYC Approved for User ID ${userId} (${user.accountType})`);
                profile.complianceStep = 'step_4';
                await profile.save();
                if (complianceAssessment) {
                    complianceAssessment.identityVerificationId = applicantId;
                    complianceAssessment.identityVerificationStatus = 'approved';
                    complianceAssessment.identityVerificationData = JSON.stringify(payload);
                    await complianceAssessment.save();
                }
            }
            else if (reviewAnswer === 'RED') {
                logger.warn(`KYC Rejected for User ID ${userId} (${user.accountType}). Reject Labels: ${reviewResult?.rejectLabels}`);
                await profile.save();
                if (complianceAssessment) {
                    complianceAssessment.identityVerificationId = applicantId;
                    complianceAssessment.identityVerificationStatus = 'rejected';
                    complianceAssessment.identityVerificationData = JSON.stringify(payload);
                    await complianceAssessment.save();
                }
            }
        }
        if (type === 'applicantPending') {
            profile.kycStatus = 'pending';
            await profile.save();
            if (complianceAssessment) {
                complianceAssessment.identityVerificationId = applicantId;
                complianceAssessment.identityVerificationStatus = 'pending';
                complianceAssessment.identityVerificationData = JSON.stringify(payload);
                await complianceAssessment.save();
            }
        }
    }
}
//# sourceMappingURL=sumsub_service.js.map