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

async function checkAccess() {
  const session = await getServerSession(authOptions);
  const perms = (session?.user as any)?.permissions || [];
  return perms.includes('TEAM_MANAGE'); // Wir nutzen vorerst dieses Recht für die Abrechnung
}

export async function GET() {
  if (!await checkAccess()) return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });

  try {
    const unbilledEntries = await prisma.timeEntry.findMany({
      where: { isBilled: false },
      include: {
        user: { select: { firstName: true, lastName: true } },
        ticket: {
          include: { customer: true }
        }
      },
      orderBy: { createdAt: 'asc' }
    });

    return NextResponse.json(unbilledEntries);
  } catch (error) {
    return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
  }
}

export async function PUT(request: Request) {
  if (!await checkAccess()) return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });

  try {
    const body = await request.json();
    const { entryIds } = body;

    if (!Array.isArray(entryIds) || entryIds.length === 0) {
      return NextResponse.json({ error: 'Keine Einträge übergeben' }, { status: 400 });
    }

    await prisma.timeEntry.updateMany({
      where: { id: { in: entryIds } },
      data: { 
        isBilled: true,
        billedAt: new Date()
      }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: 'Fehler beim Speichern' }, { status: 500 });
  }
}
