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

// GET /api/sites - List sites for user's organization
export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

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

    const sites = await db.site.findMany({
      where: {
        organizationId: session.user.organizationId,
      },
      select: {
        id: true,
        name: true,
        slug: true,
        address: true,
        phone: true,
        email: true,
        timezone: true,
        openTime: true,
        closeTime: true,
        isActive: true,
        _count: {
          select: {
            courts: {
              where: {
                isActive: true,
              },
            },
          },
        },
      },
      orderBy: {
        name: 'asc',
      },
    });

    // Transform to include court count at top level
    const transformedSites = sites.map((site) => ({
      id: site.id,
      name: site.name,
      slug: site.slug,
      address: site.address,
      phone: site.phone,
      email: site.email,
      timezone: site.timezone,
      openTime: site.openTime,
      closeTime: site.closeTime,
      isActive: site.isActive,
      courtCount: site._count.courts,
    }));

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

// POST /api/sites - Create a new site
export async function POST(request: NextRequest) {
  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;

    if (!name || !address) {
      return NextResponse.json(
        { error: 'Nombre y dirección son requeridos' },
        { status: 400 }
      );
    }

    // Generate slug from name
    const slug = name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '');

    const site = await db.site.create({
      data: {
        name,
        slug,
        address,
        phone: phone || null,
        openTime: openTime || '08:00',
        closeTime: closeTime || '22:00',
        isActive: isActive ?? true,
        organizationId: session.user.organizationId,
      },
    });

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