// server/api/hak-akses/entities.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) => {
  console.log("📥 Fetching entities from local database (users.db)");

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

    const db = new Database(dbPath);
    
    // 1. Get all users
    const users = db.prepare('SELECT id, namaLengkap, namaUser, email, realmRoles, groups FROM users ORDER BY namaLengkap ASC').all() as any[];
    
    const allRoles = new Set<string>();
    const allGroups = new Set<string>();
    const formattedUsers: any[] = [];

    users.forEach(user => {
      // Collect unique roles
      const roles = JSON.parse(user.realmRoles || '[]');
      roles.forEach((r: string) => allRoles.add(r));

      // Collect unique groups
      const groups = JSON.parse(user.groups || '[]');
      groups.forEach((g: string) => allGroups.add(g));

      // Format individual user
      formattedUsers.push({
        id: user.id,
        name: user.namaLengkap,
        username: user.namaUser,
        email: user.email,
        type: 'user'
      });
    });

    db.close();
    
    return {
      success: true,
      data: {
        roles: Array.from(allRoles).sort().map(name => ({
          id: name,
          name: name,
          type: 'role'
        })),
        groups: Array.from(allGroups).sort().map(name => ({
          id: name,
          name: name,
          type: 'group'
        })),
        users: formattedUsers
      }
    };

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