// server/api/hak-akses/members.get.ts
export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const { type, name, id } = query;

  if (!type || (!name && !id)) {
    throw createError({
      statusCode: 400,
      statusMessage: "Type and (Name or ID) are required",
    });
  }

  // Get session
  const { getSessionFromCookie } = await import('~/server/utils/sessionStore');
  const session = await getSessionFromCookie(event);
  
  if (!session) {
    throw createError({
      statusCode: 401,
      statusMessage: "Session expired",
    });
  }

  const config = useRuntimeConfig();
  const accessToken = session.accessToken;

  try {
    const issuerUrl = new URL(config.keycloakIssuer);
    const realm = issuerUrl.pathname.split('/').filter(Boolean).pop() || 'master';
    const adminBaseUrl = `${config.keycloakIssuer.replace('/realms/' + realm, '')}/admin/realms/${realm}`;

    let url = '';
    if (type === 'role') {
      url = `${adminBaseUrl}/roles/${name}/users`;
    } else if (type === 'group') {
      url = `${adminBaseUrl}/groups/${id}/members`;
    } else {
      throw new Error("Invalid type");
    }

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch members: ${response.status}`);
    }

    const members = await response.json();
    
    return {
      success: true,
      data: members.map((m: any) => ({
        id: m.id,
        username: m.username,
        email: m.email,
        firstName: m.firstName,
        lastName: m.lastName,
        name: `${m.firstName || ''} ${m.lastName || ''}`.trim() || m.username
      }))
    };

  } catch (error: any) {
    console.error("❌ Error fetching members:", error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || "Failed to fetch members",
    });
  }
});
