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

// GET /api/sites/[id] - Get a single site
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);

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

    const site = await db.site.findFirst({
      where: {
        id: params.id,
        organizationId: session.user.organizationId,
      },
      include: {
        courts: {
          where: { isActive: true },
          select: {
            id: true,
            name: true,
            type: true,
            status: true,
            pricePerHour: true,
          },
        },
      },
    });

    if (!site) {
      return NextResponse.json({ error: 'Sede no encontrada' }, { status: 404 });
    }

    return NextResponse.json({ data: site });
  } catch (error) {
    console.error('Error fetching site:', error);
    return NextResponse.json(
      { error: 'Error al obtener sede' },
      { status: 500 }
    );
  }
}

// PUT /api/sites/[id] - Update a site
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);

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

    if (!['super_admin', 'site_admin'].includes(session.user.role)) {
      return NextResponse.json({ error: 'Sin permisos' }, { status: 403 });
    }

    const body = await request.json();
    const { name, address, phone, openTime, closeTime, isActive } = body;

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

    if (!existingSite) {
      return NextResponse.json({ error: 'Sede no encontrada' }, { status: 404 });
    }

    const updateData: any = {};
    if (name !== undefined) {
      updateData.name = name;
      updateData.slug = name
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/(^-|-$)/g, '');
    }
    if (address !== undefined) updateData.address = address;
    if (phone !== undefined) updateData.phone = phone;
    if (openTime !== undefined) updateData.openTime = openTime;
    if (closeTime !== undefined) updateData.closeTime = closeTime;
    if (isActive !== undefined) updateData.isActive = isActive;

    const site = await db.site.update({
      where: { id: params.id },
      data: updateData,
    });

    return NextResponse.json({ data: site });
  } catch (error) {
    console.error('Error updating site:', error);
    return NextResponse.json(
      { error: 'Error al actualizar sede' },
      { status: 500 }
    );
  }
}

// DELETE /api/sites/[id] - Delete a site (soft delete)
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);

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

    if (session.user.role !== 'super_admin') {
      return NextResponse.json({ error: 'Sin permisos' }, { status: 403 });
    }

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

    if (!existingSite) {
      return NextResponse.json({ error: 'Sede no encontrada' }, { status: 404 });
    }

    // Soft delete
    await db.site.update({
      where: { id: params.id },
      data: { isActive: false },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error deleting site:', error);
    return NextResponse.json(
      { error: 'Error al eliminar sede' },
      { status: 500 }
    );
  }
}
