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

interface RouteContext {
  params: Promise<{ id: string }>;
}

// PUT /api/court-sessions/[id] - End a court session
export async function PUT(
  request: NextRequest,
  context: RouteContext
) {
  try {
    const session = await getServerSession(authOptions);

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

    const { id } = await context.params;

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

    if (!existingSession) {
      return NextResponse.json(
        { error: 'Court session not found' },
        { status: 404 }
      );
    }

    if (!existingSession.isActive) {
      return NextResponse.json(
        { error: 'Court session is already ended' },
        { status: 400 }
      );
    }

    // End the session
    const updatedSession = await db.courtSession.update({
      where: { id },
      data: {
        isActive: false,
        endTime: new Date(),
      },
      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(updatedSession);
  } catch (error) {
    console.error('Error ending court session:', error);
    return NextResponse.json(
      { error: 'Error ending court session' },
      { status: 500 }
    );
  }
}

// DELETE /api/court-sessions/[id] - Remove a court session entirely
export async function DELETE(
  request: NextRequest,
  context: RouteContext
) {
  try {
    const session = await getServerSession(authOptions);

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

    const { id } = await context.params;

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

    if (!existingSession) {
      return NextResponse.json(
        { error: 'Court session not found' },
        { status: 404 }
      );
    }

    await db.courtSession.delete({
      where: { id },
    });

    return NextResponse.json({ message: 'Court session deleted successfully' });
  } catch (error) {
    console.error('Error deleting court session:', error);
    return NextResponse.json(
      { error: 'Error deleting court session' },
      { status: 500 }
    );
  }
}
