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

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const setupWindows = await prisma.setupWindow.findMany({
      where: { bookingId: params.id },
      orderBy: { setupDate: 'asc' },
    });

    return NextResponse.json({ setupWindows });
  } catch (error: any) {
    console.error('Setup windows fetch error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to fetch setup windows' },
      { status: 500 }
    );
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { setupDate, setupTimeStart, setupTimeEnd, preferred, notes } = body;

    if (!setupDate || !setupTimeStart || !setupTimeEnd) {
      return NextResponse.json(
        { error: 'Setup date and times are required' },
        { status: 400 }
      );
    }

    const booking = await prisma.booking.findUnique({
      where: { id: params.id },
    });

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

    const setupWindow = await prisma.setupWindow.create({
      data: {
        bookingId: params.id,
        setupDate: new Date(setupDate),
        setupTimeStart: new Date(setupTimeStart),
        setupTimeEnd: new Date(setupTimeEnd),
        preferred: preferred || false,
        notes,
      },
    });

    return NextResponse.json({ setupWindow }, { status: 201 });
  } catch (error: any) {
    console.error('Setup window creation error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to create setup window' },
      { status: 500 }
    );
  }
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { windowId, selected, preferred, notes } = body;

    if (!windowId) {
      return NextResponse.json(
        { error: 'Window ID is required' },
        { status: 400 }
      );
    }

    if (selected) {
      await prisma.setupWindow.updateMany({
        where: { bookingId: params.id },
        data: { selected: false },
      });
    }

    const setupWindow = await prisma.setupWindow.update({
      where: { id: windowId },
      data: {
        selected: selected !== undefined ? selected : undefined,
        preferred: preferred !== undefined ? preferred : undefined,
        notes: notes !== undefined ? notes : undefined,
      },
    });

    return NextResponse.json({ setupWindow });
  } catch (error: any) {
    console.error('Setup window update error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to update setup window' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const windowId = searchParams.get('windowId');

    if (!windowId) {
      return NextResponse.json(
        { error: 'Window ID is required' },
        { status: 400 }
      );
    }

    await prisma.setupWindow.delete({
      where: { id: windowId },
    });

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('Setup window deletion error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to delete setup window' },
      { status: 500 }
    );
  }
}
