// /opt/erp-system/app/api/tickets/route.ts
import { NextResponse } from 'next/server';
import prisma from '../../../lib/prisma';
import { sendEmail } from '../../../lib/email';

export async function GET() {
  try {
    const tickets = await prisma.ticket.findMany({
      include: {
        customer: { select: { companyName: true, firstName: true, lastName: true } },
        assignedTo: { select: { id: true, firstName: true, lastName: true } }
      },
      orderBy: { updatedAt: 'desc' }
    });
    return NextResponse.json(tickets);
  } catch (error) {
    return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    
    const ticket = await prisma.ticket.create({
      data: {
        title: body.title,
        description: body.description,
        customerId: parseInt(body.customerId),
        priority: body.priority || 'MEDIUM'
      },
      include: { customer: true }
    });

    // Automatischer E-Mail-Versand an den Kunden
    if (ticket.customer.email) {
      await sendEmail({
        to: ticket.customer.email,
        subject: `Ticket #${ticket.id} eröffnet: ${ticket.title}`,
        text: `Hallo ${ticket.customer.firstName},\n\ndein Ticket wurde erfolgreich in unserem System erfasst.\n\nBetreff: ${ticket.title}\nBeschreibung:\n${ticket.description}\n\nWir kümmern uns schnellstmöglich darum.\n\nViele Grüße\nDein Support-Team`
      });
    }

    return NextResponse.json(ticket, { status: 201 });
  } catch (error) {
    return NextResponse.json({ error: 'Fehler beim Erstellen' }, { status: 500 });
  }
}
