import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { withPermission, isErrorResponse } from '@/lib/auth/api-guard';

export const dynamic = 'force-dynamic';

// GET - List all roles
export async function GET(request: NextRequest) {
  const auth = await withPermission(request, { resource: 'settings', action: 'read' });
  if (isErrorResponse(auth)) return auth;

  try {
    const roles = await prisma.role.findMany({
      include: {
        permissions: {
          include: {
            permission: true,
          },
        },
        _count: {
          select: { users: true },
        },
      },
      orderBy: { name: 'asc' },
    });

    return NextResponse.json({
      success: true,
      roles: roles.map((r: any) => ({
        ...r,
        permissions: r.permissions.map((p: any) => p.permission),
        userCount: r._count.users,
      })),
    });
  } catch (error) {
    console.error('Roles GET error:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch roles' }, { status: 500 });
  }
}
