"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.authService = void 0;
const bcryptjs_1 = __importDefault(require("bcryptjs"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const client_1 = require("@prisma/client");
const database_1 = require("../../config/database");
const env_1 = require("../../config/env");
const error_handler_1 = require("../../middleware/error-handler");
const metrics_1 = require("../../utils/metrics");
const settings_service_1 = require("../settings/settings.service");
const verification_token_service_1 = require("../../services/verification-token.service");
const email_service_1 = require("../../services/email.service");
const roles_1 = require("../../utils/roles");
const logger_1 = require("../../utils/logger");
/** Parse the roles JSON field into a UserRole[] array */
function parseRoles(user) {
    if (Array.isArray(user.roles) && user.roles.length > 0) {
        return user.roles;
    }
    return [user.role];
}
exports.authService = {
    async login(email, password) {
        const user = await database_1.prisma.user.findUnique({ where: { email } });
        if (!user) {
            (0, metrics_1.recordLoginAttempt)('failure');
            throw new error_handler_1.AppError(401, 'Invalid email or password', 'INVALID_CREDENTIALS');
        }
        const valid = await bcryptjs_1.default.compare(password, user.password);
        if (!valid) {
            (0, metrics_1.recordLoginAttempt)('failure');
            throw new error_handler_1.AppError(401, 'Invalid email or password', 'INVALID_CREDENTIALS');
        }
        // Status-specific errors
        if (user.status === client_1.UserStatus.PENDING_VERIFICATION) {
            (0, metrics_1.recordLoginAttempt)('failure');
            throw new error_handler_1.AppError(403, 'Please verify your email address before logging in', 'EMAIL_NOT_VERIFIED');
        }
        if (user.status === client_1.UserStatus.PENDING_APPROVAL) {
            (0, metrics_1.recordLoginAttempt)('failure');
            throw new error_handler_1.AppError(403, 'Your account is pending admin approval', 'ACCOUNT_PENDING');
        }
        if (user.status !== client_1.UserStatus.ACTIVE) {
            (0, metrics_1.recordLoginAttempt)('failure');
            throw new error_handler_1.AppError(403, `Account is ${user.status.toLowerCase()}`, 'ACCOUNT_INACTIVE');
        }
        if (user.expiresAt && user.expiresAt < new Date()) {
            (0, metrics_1.recordLoginAttempt)('failure');
            throw new error_handler_1.AppError(403, 'Account has expired', 'ACCOUNT_EXPIRED');
        }
        (0, metrics_1.recordLoginAttempt)('success');
        await database_1.prisma.user.update({
            where: { id: user.id },
            data: { lastLoginAt: new Date() },
        });
        // Fire-and-forget: log USER_LOGIN activity on linked Contact
        database_1.prisma.contact.findFirst({
            where: { userId: user.id, mergedIntoId: null },
        }).then(async (contact) => {
            if (contact) {
                await database_1.prisma.contactActivity.create({
                    data: {
                        contactId: contact.id,
                        type: 'USER_LOGIN',
                        title: 'User logged in',
                        description: `Login from ${user.email}`,
                    },
                });
            }
        }).catch(err => {
            logger_1.logger.warn('Login activity logging failed:', err);
        });
        const tokens = await this.generateTokenPair(user);
        const { password: _, ...userWithoutPassword } = user;
        return { user: userWithoutPassword, ...tokens };
    },
    async register(data) {
        // Check if public registration is enabled
        const settings = await settings_service_1.siteSettingsService.get();
        if (!settings.enablePublicRegistration) {
            throw new error_handler_1.AppError(403, 'Public registration is currently disabled', 'REGISTRATION_DISABLED');
        }
        const existing = await database_1.prisma.user.findUnique({ where: { email: data.email } });
        if (existing) {
            throw new error_handler_1.AppError(409, 'Email already registered', 'EMAIL_EXISTS');
        }
        const hashedPassword = await bcryptjs_1.default.hash(data.password, 12);
        // Determine if email verification is needed
        const smtpReady = await email_service_1.emailService.isSmtpConfigured();
        const requireVerification = settings.enableEmailVerification && smtpReady;
        const user = await database_1.prisma.user.create({
            data: {
                email: data.email,
                password: hashedPassword,
                name: data.name,
                phone: data.phone,
                role: client_1.UserRole.USER,
                roles: JSON.parse(JSON.stringify([client_1.UserRole.USER])),
                status: requireVerification ? client_1.UserStatus.PENDING_VERIFICATION : client_1.UserStatus.ACTIVE,
                emailVerified: !requireVerification,
                createdVia: 'SELF_REGISTRATION',
            },
        });
        // Fire-and-forget: process referral if invite code provided
        if (data.inviteCode) {
            Promise.resolve().then(() => __importStar(require('../social/referral.service'))).then(({ referralService }) => {
                referralService.processRegistrationReferral(user.id, data.inviteCode).catch(err => {
                    logger_1.logger.warn('Referral processing failed:', err);
                });
            }).catch(() => { });
        }
        // Fire-and-forget: auto-link or create Contact if People feature is enabled
        settings_service_1.siteSettingsService.get().then(async (s) => {
            if (!s.enablePeople)
                return;
            // Check for existing Contact with matching email → link
            const existingContact = await database_1.prisma.contact.findFirst({
                where: { email: { equals: data.email, mode: 'insensitive' }, userId: null, mergedIntoId: null },
            });
            if (existingContact) {
                await database_1.prisma.contact.update({ where: { id: existingContact.id }, data: { userId: user.id } });
                logger_1.logger.info(`Auto-linked contact ${existingContact.id} to registered user ${user.id}`);
            }
            else {
                // Create new Contact linked to the user
                await database_1.prisma.contact.create({
                    data: {
                        displayName: data.name || data.email,
                        firstName: data.name?.split(' ')[0] || null,
                        lastName: data.name?.split(' ').slice(1).join(' ') || null,
                        email: data.email,
                        phone: data.phone || null,
                        primarySource: 'USER',
                        userId: user.id,
                        tags: [],
                    },
                });
                logger_1.logger.info(`Auto-created contact for registered user ${user.id}`);
            }
        }).catch(err => {
            logger_1.logger.warn('Contact auto-creation on register failed:', err);
        });
        // If verification required, send email and don't issue tokens
        if (requireVerification) {
            const token = await verification_token_service_1.verificationTokenService.createToken(user.id);
            const adminUrl = env_1.env.ADMIN_URL || 'http://localhost:3000';
            const verificationUrl = `${adminUrl}/verify-email?token=${token}`;
            await email_service_1.emailService.sendVerificationEmail({
                recipientEmail: user.email,
                recipientName: user.name || 'there',
                verificationUrl,
            });
            const { password: _, ...userWithoutPassword } = user;
            return {
                user: userWithoutPassword,
                requiresVerification: true,
                message: 'Please check your email to verify your account',
            };
        }
        // No verification needed — issue tokens immediately
        const tokens = await this.generateTokenPair(user);
        const { password: _, ...userWithoutPassword } = user;
        return { user: userWithoutPassword, ...tokens };
    },
    async refreshTokens(refreshToken) {
        let payload;
        try {
            payload = jsonwebtoken_1.default.verify(refreshToken, env_1.env.JWT_REFRESH_SECRET, { algorithms: ['HS256'] });
        }
        catch {
            throw new error_handler_1.AppError(401, 'Invalid refresh token', 'INVALID_REFRESH_TOKEN');
        }
        const stored = await database_1.prisma.refreshToken.findUnique({
            where: { token: refreshToken },
            include: { user: true },
        });
        if (!stored) {
            throw new error_handler_1.AppError(401, 'Refresh token not found', 'INVALID_REFRESH_TOKEN');
        }
        // Check user status — banned/inactive users must not get new tokens
        if (stored.user.status !== client_1.UserStatus.ACTIVE) {
            await database_1.prisma.refreshToken.delete({ where: { id: stored.id } });
            throw new error_handler_1.AppError(401, 'Account is not active', 'ACCOUNT_INACTIVE');
        }
        // Check account expiry
        if (stored.user.expiresAt && stored.user.expiresAt < new Date()) {
            await database_1.prisma.refreshToken.delete({ where: { id: stored.id } });
            throw new error_handler_1.AppError(401, 'Account has expired', 'ACCOUNT_EXPIRED');
        }
        if (stored.expiresAt < new Date()) {
            await database_1.prisma.refreshToken.delete({ where: { id: stored.id } });
            throw new error_handler_1.AppError(401, 'Refresh token expired', 'REFRESH_TOKEN_EXPIRED');
        }
        // Rotate: delete old and create new atomically
        const tokens = await database_1.prisma.$transaction(async (tx) => {
            await tx.refreshToken.delete({ where: { id: stored.id } });
            const userRoles = parseRoles(stored.user);
            const accessToken = this.generateAccessToken(stored.user);
            const refreshPayload = {
                id: stored.user.id,
                email: stored.user.email,
                role: (0, roles_1.getPrimaryRole)(userRoles),
                roles: userRoles,
            };
            const refreshToken = jsonwebtoken_1.default.sign(refreshPayload, env_1.env.JWT_REFRESH_SECRET, {
                algorithm: 'HS256',
                expiresIn: env_1.env.JWT_REFRESH_EXPIRY,
            });
            const decoded = jsonwebtoken_1.default.decode(refreshToken);
            const expiresAt = new Date(decoded.exp * 1000);
            await tx.refreshToken.create({
                data: {
                    token: refreshToken,
                    userId: stored.user.id,
                    expiresAt,
                },
            });
            return { accessToken, refreshToken };
        });
        const { password: _, ...userWithoutPassword } = stored.user;
        return { user: userWithoutPassword, ...tokens };
    },
    async logout(refreshToken) {
        await database_1.prisma.refreshToken.deleteMany({ where: { token: refreshToken } });
    },
    generateAccessToken(user) {
        const userRoles = parseRoles(user);
        const payload = {
            id: user.id,
            email: user.email,
            role: (0, roles_1.getPrimaryRole)(userRoles),
            roles: userRoles,
        };
        return jsonwebtoken_1.default.sign(payload, env_1.env.JWT_ACCESS_SECRET, {
            algorithm: 'HS256',
            expiresIn: env_1.env.JWT_ACCESS_EXPIRY,
        });
    },
    async generateRefreshToken(user) {
        const userRoles = parseRoles(user);
        const payload = {
            id: user.id,
            email: user.email,
            role: (0, roles_1.getPrimaryRole)(userRoles),
            roles: userRoles,
        };
        const token = jsonwebtoken_1.default.sign(payload, env_1.env.JWT_REFRESH_SECRET, {
            algorithm: 'HS256',
            expiresIn: env_1.env.JWT_REFRESH_EXPIRY,
        });
        const decoded = jsonwebtoken_1.default.decode(token);
        const expiresAt = new Date(decoded.exp * 1000);
        await database_1.prisma.refreshToken.create({
            data: {
                token,
                userId: user.id,
                expiresAt,
            },
        });
        return token;
    },
    async generateTokenPair(user) {
        const accessToken = this.generateAccessToken(user);
        const refreshToken = await this.generateRefreshToken(user);
        return { accessToken, refreshToken };
    },
};
//# sourceMappingURL=auth.service.js.map