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) {
  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 available = searchParams.get('available');

    const where: any = { role: 'DRIVER' };
    if (available === 'true') where.available = true;
    if (available === 'false') where.available = false;

    const drivers = await prisma.user.findMany({
      where,
      select: {
        id: true,
        name: true,
        email: true,
        phoneNumber: true,
        vehiclePlate: true,
        vehicleModel: true,
        active: true,
        available: true,
        createdAt: true,
        _count: {
          select: {
            driverTours: true,
          },
        },
      },
      orderBy: {
        name: 'asc',
      },
    });

    return NextResponse.json({ drivers });
  } catch (error: any) {
    console.error('Driver fetch error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to fetch drivers' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  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,
    } = body;

    if (!name || !email || !password) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    const existingUser = await prisma.user.findUnique({
      where: { email },
    });

    if (existingUser) {
      return NextResponse.json(
        { error: 'Email already in use' },
        { status: 400 }
      );
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    const driver = await prisma.user.create({
      data: {
        name,
        email,
        password: hashedPassword,
        phoneNumber,
        vehiclePlate,
        vehicleModel,
        role: 'DRIVER',
        active: true,
        available: true,
      },
      select: {
        id: true,
        name: true,
        email: true,
        phoneNumber: true,
        vehiclePlate: true,
        vehicleModel: true,
        active: true,
        available: true,
        createdAt: true,
      },
    });

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