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

export async function GET(
  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 driver = await prisma.user.findUnique({
      where: { id: params.id, role: 'DRIVER' },
      select: {
        id: true,
        name: true,
        email: true,
        phoneNumber: true,
        vehiclePlate: true,
        vehicleModel: true,
        active: true,
        available: true,
        createdAt: true,
        driverTours: {
          include: {
            bookings: {
              select: {
                id: true,
                bookingNumber: true,
                eventDate: true,
                eventLocation: true,
                customerName: true,
              },
            },
          },
          orderBy: {
            tourDate: 'desc',
          },
          take: 10,
        },
      },
    });

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

    return NextResponse.json({ driver });
  } catch (error: any) {
    console.error('Driver fetch error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to fetch driver' },
      { 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 {
      name,
      email,
      password,
      phoneNumber,
      vehiclePlate,
      vehicleModel,
      active,
      available,
    } = body;

    const updateData: any = {};
    if (name !== undefined) updateData.name = name;
    if (email !== undefined) updateData.email = email;
    if (phoneNumber !== undefined) updateData.phoneNumber = phoneNumber;
    if (vehiclePlate !== undefined) updateData.vehiclePlate = vehiclePlate;
    if (vehicleModel !== undefined) updateData.vehicleModel = vehicleModel;
    if (active !== undefined) updateData.active = active;
    if (available !== undefined) updateData.available = available;
    
    if (password) {
      updateData.password = await bcrypt.hash(password, 10);
    }

    const driver = await prisma.user.update({
      where: { id: params.id },
      data: updateData,
      select: {
        id: true,
        name: true,
        email: true,
        phoneNumber: true,
        vehiclePlate: true,
        vehicleModel: true,
        active: true,
        available: true,
      },
    });

    return NextResponse.json({ driver });
  } catch (error: any) {
    console.error('Driver update error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to update driver' },
      { 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 });
    }

    await prisma.user.delete({
      where: { id: params.id },
    });

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