// /opt/erp-system/app/api/roles/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');
}

export async function GET() {
  if (!await checkAccess()) return NextResponse.json({ error: 'Access denied' }, { status: 403 });
  
  try {
    const roles = await prisma.role.findMany({
      include: { _count: { select: { users: true } } },
      orderBy: { id: 'asc' }
    });
    return NextResponse.json(roles);
  } catch (error) {
    return NextResponse.json({ error: 'Fehler beim Laden' }, { status: 500 });
  }
}

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

  try {
    const body = await request.json();
    const newRole = await prisma.role.create({
      data: { name: body.name, permissions: body.permissions }
    });
    return NextResponse.json(newRole, { status: 201 });
  } catch (error: any) {
    if (error.code === 'P2002') return NextResponse.json({ error: 'Rollenname existiert bereits.' }, { status: 400 });
    return NextResponse.json({ error: 'Fehler beim Speichern' }, { status: 500 });
  }
}

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

  try {
    const body = await request.json();
    const updatedRole = await prisma.role.update({
      where: { id: body.id },
      data: { name: body.name, permissions: body.permissions }
    });
    return NextResponse.json(updatedRole, { status: 200 });
  } catch (error) {
    return NextResponse.json({ error: 'Fehler beim Speichern' }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  const session = await getServerSession(authOptions);
  const perms = (session?.user as any)?.permissions || [];
  if (!perms.includes('DATA_DELETE')) return NextResponse.json({ error: 'Keine Löschberechtigung' }, { status: 403 });

  try {
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    if (!id) return NextResponse.json({ error: 'ID fehlt' }, { status: 400 });

    const roleId = parseInt(id);

    // Check if users are still assigned
    const usersWithRole = await prisma.user.count({ where: { roleId } });
    if (usersWithRole > 0) {
      return NextResponse.json({ error: `Diese Gruppe ist noch ${usersWithRole} Nutzer(n) zugeordnet. Bitte weise sie zuerst einer anderen Gruppe zu.` }, { status: 400 });
    }

    await prisma.role.delete({ where: { id: roleId } });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
  }
}
