import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';

// GET /api/live - Get complete live court status
export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { searchParams } = new URL(request.url);
    const siteId = searchParams.get('siteId');

    // Build where clause for courts
    const courtWhere: {
      isActive: boolean;
      site: { organizationId: string; id?: string };
    } = {
      isActive: true,
      site: {
        organizationId: session.user.organizationId,
      },
    };

    if (siteId) {
      courtWhere.site.id = siteId;
    } else if (session.user.siteId) {
      courtWhere.site.id = session.user.siteId;
    }

    const now = new Date();
    const endOfHour = new Date(now.getTime() + 30 * 60 * 1000); // 30 minutes from now

    // Get all courts with their active sessions AND current bookings
    const courts = await db.court.findMany({
      where: courtWhere,
      include: {
        sessions: {
          where: { isActive: true },
          include: {
            client: { select: { id: true, firstName: true, lastName: true, phone: true } },
          },
        },
        bookings: {
          where: {
            startTime: { lte: endOfHour },
            endTime: { gte: now },
            status: { in: ['CONFIRMED', 'PENDING'] },
          },
          include: {
            client: { select: { id: true, firstName: true, lastName: true } },
          },
        },
        site: { select: { id: true, name: true } },
      },
      orderBy: { displayOrder: 'asc' },
    });

    // Compute status for each court and transform to frontend shape
    const courtsWithStatus = courts.map((court) => {
      let status: 'available' | 'active' | 'open_play' | 'booked';

      if (court.sessions.length > 0) {
        status = court.isOpenPlay ? 'open_play' : 'active';
      } else if (court.isOpenPlay) {
        status = 'open_play';
      } else if (court.bookings.length > 0) {
        status = 'booked';
      } else {
        status = 'available';
      }

      // Transform sessions to players array for frontend
      const players = court.sessions.map((session) => ({
        id: session.client?.id || session.id,
        firstName: session.client?.firstName,
        lastName: session.client?.lastName,
        walkInName: session.walkInName,
        checkedInAt: session.startTime.toISOString(),
        sessionId: session.id,
      }));

      // Get upcoming booking info
      const upcomingBooking = court.bookings.length > 0 ? {
        startTime: court.bookings[0].startTime.toISOString(),
        clientName: court.bookings[0].client
          ? `${court.bookings[0].client.firstName} ${court.bookings[0].client.lastName}`
          : 'Walk-in',
      } : undefined;

      return {
        id: court.id,
        name: court.name,
        type: court.type,
        isOpenPlay: court.isOpenPlay,
        status,
        players,
        upcomingBooking,
      };
    });

    return NextResponse.json(courtsWithStatus);
  } catch (error) {
    console.error('Error fetching live court status:', error);
    return NextResponse.json(
      { error: 'Error fetching live court status' },
      { status: 500 }
    );
  }
}
