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

// GET /api/courts - List courts filtered by organization and optionally by siteId
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 the where clause
    const whereClause: {
      site: {
        organizationId: string;
        id?: string;
      };
    } = {
      site: {
        organizationId: session.user.organizationId,
      },
    };

    // If a specific siteId is provided in query params, use it
    if (siteId) {
      whereClause.site.id = siteId;
    } else if (session.user.siteId) {
      // Otherwise, if user has a siteId assigned, filter by that
      whereClause.site.id = session.user.siteId;
    }

    const courts = await db.court.findMany({
      where: whereClause,
      include: {
        site: {
          select: {
            id: true,
            name: true,
            slug: true,
            openTime: true,
            closeTime: true,
            timezone: true,
          },
        },
      },
      orderBy: [
        { site: { name: 'asc' } },
        { displayOrder: 'asc' },
        { name: 'asc' },
      ],
    });

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

// POST /api/courts - Create a new court
export async function POST(request: NextRequest) {
  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 body = await request.json();
    const {
      siteId,
      name,
      type,
      status,
      pricePerHour,
      description,
      features,
      displayOrder,
      isActive,
    } = body;

    // Validate required fields
    if (!siteId || !name || pricePerHour === undefined) {
      return NextResponse.json(
        { error: 'Missing required fields: siteId, name, pricePerHour' },
        { status: 400 }
      );
    }

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

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

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

    const court = await db.court.create({
      data: {
        siteId,
        name,
        type: type || 'INDOOR',
        status: status || 'AVAILABLE',
        pricePerHour,
        description: description || null,
        features: features || [],
        displayOrder: displayOrder ?? 0,
        isActive: isActive ?? true,
      },
      include: {
        site: {
          select: {
            id: true,
            name: true,
            slug: true,
            openTime: true,
            closeTime: true,
            timezone: true,
          },
        },
      },
    });

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