"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOrCreateSession = getOrCreateSession;
const database_1 = require("../../../config/database");
const logger_1 = require("../../../utils/logger");
/**
 * Session service for anonymous user tracking
 * Reads X-Session-ID header, creates session if doesn't exist
 */
async function getOrCreateSession(request) {
    const sessionId = request.headers['x-session-id'];
    if (!sessionId) {
        throw new Error('X-Session-ID header is required');
    }
    // Check if session exists
    const existingSession = await database_1.prisma.session.findUnique({
        where: { id: sessionId },
    });
    if (existingSession) {
        // Update last seen timestamp
        await database_1.prisma.session.update({
            where: { id: sessionId },
            data: { lastSeenAt: new Date() },
        });
        return sessionId;
    }
    // Create new session
    try {
        await database_1.prisma.session.create({
            data: {
                id: sessionId,
                ipAddress: request.ip,
                userAgent: request.headers['user-agent'] || 'Unknown',
                lastSeenAt: new Date(),
                firstSeenAt: new Date(),
                visitCount: 1,
            },
        });
        logger_1.logger.info(`Created new session: ${sessionId}`);
        return sessionId;
    }
    catch (error) {
        // Handle race condition where session was created between check and create
        if (error.code === 'P2002') {
            logger_1.logger.warn(`Session ${sessionId} already exists (race condition)`);
            return sessionId;
        }
        throw error;
    }
}
//# sourceMappingURL=session.service.js.map