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

// GET: Fetch contractor badges
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const contractorId = searchParams.get('contractorId');
    const active = searchParams.get('active') === 'true';
    const verified = searchParams.get('verified') === 'true';

    const where: any = {};
    if (contractorId) where.contractorId = contractorId;
    if (active) where.isActive = true;
    if (verified) where.isVerified = true;

    // Check for expired badges
    const now = new Date();
    if (active) {
      where.OR = [
        { expiryDate: null },
        { expiryDate: { gt: now } },
      ];
    }

    const badges = await prisma.contractorBadge.findMany({
      where,
      orderBy: [
        { isVerified: 'desc' },
        { issuedDate: 'desc' },
      ],
    });

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

// POST: Create a new badge (admin only)
export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const {
      contractorId,
      badgeType,
      name,
      description,
      issuedDate,
      expiryDate,
      issuer,
      certificateNumber,
    } = body;

    const badge = await prisma.contractorBadge.create({
      data: {
        contractorId,
        badgeType,
        name,
        description,
        issuedDate: new Date(issuedDate),
        expiryDate: expiryDate ? new Date(expiryDate) : null,
        issuer,
        certificateNumber,
        isVerified: true,
        verifiedBy: session.user.id,
        verifiedAt: new Date(),
      },
    });

    return NextResponse.json({ badge }, { status: 201 });
  } catch (error) {
    console.error('Error creating badge:', error);
    return NextResponse.json(
      { error: 'Failed to create badge' },
      { status: 500 }
    );
  }
}

// PUT: Update badge (verify, deactivate, etc.)
export async function PUT(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { badgeId, isVerified, isActive, expiryDate } = body;

    const updateData: any = {};
    if (typeof isVerified === 'boolean') {
      updateData.isVerified = isVerified;
      if (isVerified) {
        updateData.verifiedBy = session.user.id;
        updateData.verifiedAt = new Date();
      }
    }
    if (typeof isActive === 'boolean') updateData.isActive = isActive;
    if (expiryDate) updateData.expiryDate = new Date(expiryDate);

    const badge = await prisma.contractorBadge.update({
      where: { id: badgeId },
      data: updateData,
    });

    return NextResponse.json({ badge });
  } catch (error) {
    console.error('Error updating badge:', error);
    return NextResponse.json(
      { error: 'Failed to update badge' },
      { status: 500 }
    );
  }
}
