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

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

    const equipment = await prisma.equipment.findMany({
      include: {
        location: true,
        project: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    return NextResponse.json({ equipment });
  } catch (error) {
    console.error('Error fetching equipment:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

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

    const data = await request.json();

    const equipment = await prisma.equipment.create({
      data: {
        name: data.name,
        type: data.type,
        brand: data.brand,
        model: data.model,
        serialNumber: data.serialNumber,
        quantity: data.quantity || 1,
        status: data.status || 'AVAILABLE',
        locationId: data.locationId,
        projectId: data.projectId,
        notes: data.notes,
        purchaseDate: data.purchaseDate ? new Date(data.purchaseDate) : null,
        purchasePrice: data.purchasePrice,
        minStockLevel: data.minStockLevel,
        currentStock: data.currentStock,
      },
      include: {
        location: true,
        project: true,
      },
    });

    return NextResponse.json({ equipment });
  } catch (error) {
    console.error('Error creating equipment:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
