// /opt/erp-system/app/api/search/route.ts
import { NextResponse } from 'next/server';
import prisma from '../../../lib/prisma';
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]/route";

export async function GET(request: Request) {
  const session = await getServerSession(authOptions);
  
  // Nur Team-Mitglieder dürfen die globale Suche nutzen
  if (!session || (session.user as any).userType !== 'TEAM') {
    return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const q = searchParams.get('q');

  if (!q || q.length < 2) {
    return NextResponse.json({ tickets: [], customers: [] });
  }

  // Prüfen, ob nach einer exakten Ticket-ID gesucht wird (z.B. "12")
  const isNumber = !isNaN(Number(q));

  try {
    const [tickets, customers] = await Promise.all([
      prisma.ticket.findMany({
        where: {
          OR: [
            isNumber ? { id: Number(q) } : {},
            { title: { contains: q, mode: 'insensitive' } },
            { description: { contains: q, mode: 'insensitive' } }
          ].filter(condition => Object.keys(condition).length > 0)
        },
        take: 20, // Begrenzung für Performance
        include: { customer: { select: { firstName: true, lastName: true, companyName: true } } }
      }),
      prisma.customer.findMany({
        where: {
          OR: [
            { firstName: { contains: q, mode: 'insensitive' } },
            { lastName: { contains: q, mode: 'insensitive' } },
            { companyName: { contains: q, mode: 'insensitive' } },
            { email: { contains: q, mode: 'insensitive' } }
          ]
        },
        take: 20
      })
    ]);

    return NextResponse.json({ tickets, customers });
  } catch (error) {
    return NextResponse.json({ error: 'Fehler bei der Suche' }, { status: 500 });
  }
}
