// server/api/hak-akses/members.get.ts
import Database from 'better-sqlite3';
import { join } from 'path';
import { existsSync } from 'fs';

// Helper to get database path
const getDbPath = () => {
  return join(process.cwd(), 'data', 'users.db');
};

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",
    });
  }

  try {
    const dbPath = getDbPath();
    if (!existsSync(dbPath)) {
      return { success: true, data: [] };
    }

    const db = new Database(dbPath);
    const users = db.prepare('SELECT id, namaLengkap, namaUser, email, realmRoles, groups FROM users').all() as any[];
    db.close();

    let filteredUsers = [];

    if (type === 'role') {
      filteredUsers = users.filter(user => {
        const roles = JSON.parse(user.realmRoles || '[]');
        return roles.includes(name);
      });
    } else if (type === 'group') {
      filteredUsers = users.filter(user => {
        const groups = JSON.parse(user.groups || '[]');
        return groups.includes(name);
      });
    } else if (type === 'user') {
      // For type 'user', name is the username
      filteredUsers = users.filter(user => user.namaUser === name);
    }

    return {
      success: true,
      data: filteredUsers.map((m: any) => ({
        id: m.id,
        username: m.namaUser,
        email: m.email,
        name: m.namaLengkap
      }))
    };

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