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

// GET: Fetch materials catalog
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const category = searchParams.get('category');
    const available = searchParams.get('available') === 'true';
    const search = searchParams.get('search');

    const where: any = {};
    if (category) where.category = category;
    if (available) where.isAvailable = true;
    if (search) {
      where.OR = [
        { name: { contains: search, mode: 'insensitive' } },
        { description: { contains: search, mode: 'insensitive' } },
        { tags: { has: search } },
      ];
    }

    const materials = await prisma.material.findMany({
      where,
      orderBy: [
        { isAvailable: 'desc' },
        { name: 'asc' },
      ],
    });

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

// POST: Create a new material (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 {
      category,
      name,
      description,
      basePrice,
      unit,
      brand,
      color,
      durability,
      warranty,
      imageUrl,
      thumbnailUrl,
      features,
      tags,
    } = body;

    const material = await prisma.material.create({
      data: {
        category,
        name,
        description,
        basePrice,
        unit,
        brand,
        color,
        durability,
        warranty,
        imageUrl,
        thumbnailUrl,
        features,
        tags: tags || [],
      },
    });

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

// PUT: Update material
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 { materialId, ...updateData } = body;

    const material = await prisma.material.update({
      where: { id: materialId },
      data: updateData,
    });

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