// /opt/erp-system/app/api/dashboard/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() {
  try {
    const session = await getServerSession(authOptions);
    if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });

    const userId = parseInt((session.user as any).id);
    const userType = (session.user as any).userType;

    // ----------------------------------------------------
    // METRIKEN FÜR KUNDEN
    // ----------------------------------------------------
    if (userType === 'CUSTOMER') {
      const [openTicketsCount, closedTicketsCount, recentTickets] = await Promise.all([
        prisma.ticket.count({
          where: { customerId: userId, status: { in: ['OPEN', 'IN_PROGRESS', 'WAITING_FOR_CUSTOMER'] } }
        }),
        prisma.ticket.count({
          where: { customerId: userId, status: { in: ['RESOLVED', 'CLOSED'] } }
        }),
        prisma.ticket.findMany({
          where: { customerId: userId },
          take: 5,
          orderBy: { updatedAt: 'desc' },
          include: { customer: { select: { companyName: true, firstName: true, lastName: true } } }
        })
      ]);

      return NextResponse.json({
        userType: 'CUSTOMER',
        openTickets: openTicketsCount,
        closedTickets: closedTicketsCount,
        recentTickets
      });
    }

    // ----------------------------------------------------
    // METRIKEN FÜR TEAM-MITARBEITER
    // ----------------------------------------------------
    const [openTicketsCount, myTicketsCount, recentTickets, timeEntries] = await Promise.all([
      prisma.ticket.count({
        where: { status: { in: ['OPEN', 'IN_PROGRESS', 'WAITING_FOR_CUSTOMER'] } }
      }),
      prisma.ticket.count({
        where: { assignedToId: userId, status: { in: ['OPEN', 'IN_PROGRESS', 'WAITING_FOR_CUSTOMER'] } }
      }),
      prisma.ticket.findMany({
        take: 5,
        orderBy: { updatedAt: 'desc' },
        include: { customer: { select: { companyName: true, firstName: true, lastName: true } } }
      }),
      prisma.timeEntry.aggregate({
        _sum: { durationMins: true }
      })
    ]);

    const totalMinutes = timeEntries._sum.durationMins || 0;
    const totalHours = totalMinutes / 60;

    return NextResponse.json({
      userType: 'TEAM',
      openTickets: openTicketsCount,
      myTickets: myTicketsCount,
      recentTickets,
      totalHours
    });

  } catch (error) {
    console.error("Dashboard Fehler:", error);
    return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
  }
}
