import { FastifyInstance } from 'fastify';
import { prisma } from '../../config/database.js';
import { authMiddleware } from '../middleware/auth.middleware.js';
import { startSessionSchema, paginationSchema } from '../middleware/validate.js';
import { successResponse, errorResponse, paginatedResponse } from '../../utils/helpers.js';

export async function sessionRoutes(app: FastifyInstance) {
  app.addHook('preHandler', authMiddleware);

  // GET /api/v1/sessions
  app.get('/', async (request, reply) => {
    const { page, limit } = paginationSchema.parse(request.query);
    const tenantId = request.tenantId!;
    const skip = (page - 1) * limit;

    const [sessions, total] = await Promise.all([
      prisma.liveSession.findMany({
        where: { tenantId },
        skip,
        take: limit,
        orderBy: { createdAt: 'desc' },
        include: {
          _count: { select: { auctionItems: true } },
        },
      }),
      prisma.liveSession.count({ where: { tenantId } }),
    ]);

    return paginatedResponse(reply, sessions, total, page, limit);
  });

  // POST /api/v1/sessions/start
  app.post('/start', async (request, reply) => {
    const parsed = startSessionSchema.safeParse(request.body);
    if (!parsed.success) {
      return errorResponse(reply, 'Validation error', 400, parsed.error.flatten());
    }

    const tenantId = request.tenantId!;

    // Check for already active session
    const activeSession = await prisma.liveSession.findFirst({
      where: { tenantId, status: 'live' },
    });
    if (activeSession) {
      return errorResponse(reply, 'There is already an active live session', 409);
    }

    const session = await prisma.liveSession.create({
      data: {
        tenantId,
        title: parsed.data.title,
        igLiveVideoId: parsed.data.igLiveVideoId,
        status: 'live',
        startedAt: new Date(),
        settings: (parsed.data.settings ?? {}) as any,
      },
    });

    return successResponse(reply, session, 201);
  });

  // PUT /api/v1/sessions/:id/end
  app.put('/:id/end', async (request, reply) => {
    const { id } = request.params as { id: string };
    const tenantId = request.tenantId!;

    const session = await prisma.liveSession.findFirst({
      where: { id, tenantId },
    });
    if (!session) return errorResponse(reply, 'Session not found', 404);
    if (session.status === 'ended') {
      return errorResponse(reply, 'Session already ended', 400);
    }

    // Close all active auction items
    await prisma.auctionItem.updateMany({
      where: {
        liveSessionId: id,
        status: { in: ['active', 'countdown'] },
      },
      data: { status: 'cancelled', closedAt: new Date() },
    });

    const updated = await prisma.liveSession.update({
      where: { id },
      data: { status: 'ended', endedAt: new Date() },
    });

    return successResponse(reply, updated);
  });

  // GET /api/v1/sessions/:id/stats
  app.get('/:id/stats', async (request, reply) => {
    const { id } = request.params as { id: string };
    const tenantId = request.tenantId!;

    const session = await prisma.liveSession.findFirst({
      where: { id, tenantId },
      include: {
        auctionItems: {
          include: {
            _count: { select: { bids: true, cartEvents: true } },
            product: { select: { name: true, imageUrl: true } },
          },
        },
      },
    });

    if (!session) return errorResponse(reply, 'Session not found', 404);
    return successResponse(reply, session);
  });
}
