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

// GET /api/court-sessions - List all active court sessions
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 courtId = searchParams.get('courtId');
    const siteId = searchParams.get('siteId');

    // Build where clause
    const whereClause: {
      isActive: boolean;
      courtId?: string;
      court?: { siteId?: string; site: { organizationId: string } };
    } = {
      isActive: true,
      court: {
        site: {
          organizationId: session.user.organizationId,
        },
      },
    };

    if (courtId) {
      whereClause.courtId = courtId;
    }

    if (siteId) {
      whereClause.court = {
        ...whereClause.court!,
        siteId,
      };
    } else if (session.user.siteId) {
      whereClause.court = {
        ...whereClause.court!,
        siteId: session.user.siteId,
      };
    }

    const sessions = await db.courtSession.findMany({
      where: whereClause,
      include: {
        court: { select: { id: true, name: true, type: true, isOpenPlay: true, siteId: true } },
        client: { select: { id: true, firstName: true, lastName: true, phone: true } },
      },
      orderBy: { startTime: 'desc' },
    });

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

// POST /api/court-sessions - Check in a player to a court
export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

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

    const body = await request.json();
    const { courtId, clientId, walkInName, notes } = body;

    // Validate required fields
    if (!courtId) {
      return NextResponse.json(
        { error: 'courtId is required' },
        { status: 400 }
      );
    }

    // Must have either clientId or walkInName
    if (!clientId && !walkInName) {
      return NextResponse.json(
        { error: 'Either clientId or walkInName is required' },
        { status: 400 }
      );
    }

    // Verify court exists and belongs to user's organization
    const court = await db.court.findFirst({
      where: {
        id: courtId,
        site: {
          organizationId: session.user.organizationId,
        },
      },
    });

    if (!court) {
      return NextResponse.json(
        { error: 'Court not found or does not belong to your organization' },
        { status: 404 }
      );
    }

    // If clientId is provided, verify client exists
    if (clientId) {
      const client = await db.client.findFirst({
        where: {
          id: clientId,
          organizationId: session.user.organizationId,
        },
      });

      if (!client) {
        return NextResponse.json(
          { error: 'Client not found or does not belong to your organization' },
          { status: 404 }
        );
      }
    }

    // Create the court session
    const courtSession = await db.courtSession.create({
      data: {
        courtId,
        clientId: clientId || null,
        walkInName: walkInName || null,
        notes: notes || null,
        isActive: true,
      },
      include: {
        court: { select: { id: true, name: true, type: true, isOpenPlay: true, siteId: true } },
        client: { select: { id: true, firstName: true, lastName: true, phone: true } },
      },
    });

    return NextResponse.json(courtSession, { status: 201 });
  } catch (error) {
    console.error('Error creating court session:', error);
    return NextResponse.json(
      { error: 'Error creating court session' },
      { status: 500 }
    );
  }
}
