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 }>;
}

// GET /api/courts/[id] - Get a single court by ID
export async function GET(
  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;

    const court = await db.court.findFirst({
      where: {
        id,
        site: {
          organizationId: session.user.organizationId,
        },
      },
      include: {
        site: {
          select: {
            id: true,
            name: true,
            slug: true,
            openTime: true,
            closeTime: true,
            timezone: true,
            address: true,
            phone: true,
            email: true,
          },
        },
      },
    });

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

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

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

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

    // Check if user has admin role
    const allowedRoles = ['SUPER_ADMIN', 'SITE_ADMIN'];
    if (!allowedRoles.includes(session.user.role)) {
      return NextResponse.json(
        { error: 'Forbidden: Insufficient permissions' },
        { status: 403 }
      );
    }

    const { id } = await context.params;

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

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

    // If user is SITE_ADMIN, verify they have access to this site
    if (session.user.role === 'SITE_ADMIN' && session.user.siteId !== existingCourt.siteId) {
      return NextResponse.json(
        { error: 'Forbidden: You do not have access to this court' },
        { status: 403 }
      );
    }

    const body = await request.json();
    const {
      name,
      type,
      status,
      pricePerHour,
      description,
      features,
      displayOrder,
      isActive,
    } = body;

    const court = await db.court.update({
      where: { id },
      data: {
        ...(name !== undefined && { name }),
        ...(type !== undefined && { type }),
        ...(status !== undefined && { status }),
        ...(pricePerHour !== undefined && { pricePerHour }),
        ...(description !== undefined && { description }),
        ...(features !== undefined && { features }),
        ...(displayOrder !== undefined && { displayOrder }),
        ...(isActive !== undefined && { isActive }),
      },
      include: {
        site: {
          select: {
            id: true,
            name: true,
            slug: true,
            openTime: true,
            closeTime: true,
            timezone: true,
          },
        },
      },
    });

    return NextResponse.json(court);
  } catch (error) {
    console.error('Error updating court:', error);
    return NextResponse.json(
      { error: 'Failed to update court' },
      { status: 500 }
    );
  }
}

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

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

    // Check if user has admin role
    const allowedRoles = ['SUPER_ADMIN', 'SITE_ADMIN'];
    if (!allowedRoles.includes(session.user.role)) {
      return NextResponse.json(
        { error: 'Forbidden: Insufficient permissions' },
        { status: 403 }
      );
    }

    const { id } = await context.params;

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

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

    // If user is SITE_ADMIN, verify they have access to this site
    if (session.user.role === 'SITE_ADMIN' && session.user.siteId !== existingCourt.siteId) {
      return NextResponse.json(
        { error: 'Forbidden: You do not have access to this court' },
        { status: 403 }
      );
    }

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

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