import { prisma } from '../../../config/database';
import { FastifyRequest } from 'fastify';
import { logger } from '../../../utils/logger';

/**
 * Session service for anonymous user tracking
 * Reads X-Session-ID header, creates session if doesn't exist
 */

export async function getOrCreateSession(request: FastifyRequest): Promise<string> {
  const sessionId = request.headers['x-session-id'] as string | undefined;

  if (!sessionId) {
    throw new Error('X-Session-ID header is required');
  }

  // Check if session exists
  const existingSession = await prisma.session.findUnique({
    where: { id: sessionId },
  });

  if (existingSession) {
    // Update last seen timestamp
    await prisma.session.update({
      where: { id: sessionId },
      data: { lastSeenAt: new Date() },
    });
    return sessionId;
  }

  // Create new session
  try {
    await prisma.session.create({
      data: {
        id: sessionId,
        ipAddress: request.ip,
        userAgent: request.headers['user-agent'] || 'Unknown',
        lastSeenAt: new Date(),
        firstSeenAt: new Date(),
        visitCount: 1,
      },
    });

    logger.info(`Created new session: ${sessionId}`);
    return sessionId;
  } catch (error: any) {
    // Handle race condition where session was created between check and create
    if (error.code === 'P2002') {
      logger.warn(`Session ${sessionId} already exists (race condition)`);
      return sessionId;
    }
    throw error;
  }
}
