// server/api/permission.get.ts
// Proxy endpoint to fetch permissions from backend API with placeholder fallback

// Placeholder data for testing (matching the example API response)
const PLACEHOLDER_PERMISSIONS: Record<string, any> = {
  'superadmin_STIM': {
    message: "Data permission berhasil diambil",
    data: [
      {
        id: 1,
        create: false,
        read: true,
        update: false,
        disable: false,
        delete: false,
        active: true,
        pagename: "Halaman Utama",
        pagesID: 1,
        level: 1,
        sort: 1
      },
      {
        id: 6,
        create: false,
        read: true,
        update: false,
        disable: false,
        delete: false,
        active: true,
        pagename: "Halaman Utama",
        pagesID: 1,
        level: 1,
        sort: 1
      },
      {
        id: 2,
        create: false,
        read: true,
        update: false,
        disable: false,
        delete: false,
        active: true,
        pagename: "Pengaturan",
        pagesID: 2,
        level: 1,
        sort: 2
      },
      {
        id: 3,
        create: false,
        read: true,
        update: false,
        disable: true,
        delete: false,
        active: true,
        pagename: "Halaman",
        pagesID: 3,
        level: 2,
        sort: 3,
        parent: 2
      },
      {
        id: 7,
        create: false,
        read: true,
        update: false,
        disable: true,
        delete: false,
        active: true,
        pagename: "Dashboard",
        pagesID: 15,
        level: 1,
        sort: 2
      }
    ],
    meta: {
      count: 5,
      total: 5
    }
  }
};

// Mapping untuk role dan group yang berbeda
const roleGroupMapping: Record<string, { role: string; group: string }> = {
  // Mapping untuk role default-roles-sandbox dengan group Instalasi STIM
  'default-roles-sandbox_instalasi stim': { role: 'superadmin', group: 'STIM' },
  'default-roles-sandbox_stim': { role: 'superadmin', group: 'STIM' },
  // Tambahkan mapping lain jika diperlukan
};

// Normalize group name (remove "Instalasi" prefix if exists)
const normalizeGroup = (group: string): string => {
  const normalized = group.trim();
  // Jika group mengandung "Instalasi STIM", ambil hanya "STIM"
  if (normalized.toLowerCase().includes('instalasi')) {
    const parts = normalized.split(/\s+/);
    const stimIndex = parts.findIndex(p => p.toLowerCase() === 'stim');
    if (stimIndex !== -1) {
      return 'STIM';
    }
  }
  // Jika group adalah "Instalasi STIM", return "STIM"
  if (normalized.toLowerCase() === 'instalasi stim') {
    return 'STIM';
  }
  return normalized.toUpperCase();
};

// Normalize role name
const normalizeRole = (role: string): string => {
  const normalized = role.toLowerCase().trim();
  // Mapping khusus untuk role default
  if (normalized === 'default-roles-sandbox') {
    return 'superadmin';
  }
  return normalized;
};

// Get placeholder data for a role+group combination
const getPlaceholderData = (role: string, group: string): any | null => {
  const normalizedRole = normalizeRole(role);
  const normalizedGroup = normalizeGroup(group);
  const key = `${normalizedRole}_${normalizedGroup}`;
  
  // Check direct match
  let data = PLACEHOLDER_PERMISSIONS[key];
  if (data) return data;
  
  // Check mapping
  const mappingKey = `${role.toLowerCase()}_${group.toLowerCase()}`;
  const mapping = roleGroupMapping[mappingKey];
  if (mapping) {
    const mappedKey = `${mapping.role.toLowerCase()}_${mapping.group.toUpperCase()}`;
    return PLACEHOLDER_PERMISSIONS[mappedKey] || null;
  }
  
  return null;
};

export default defineEventHandler(async (event) => {
  console.log("🔐 Permission endpoint called");

  const query = getQuery(event);
  const roles = query.roles as string | string[];
  const groups = query.groups as string | string[];

  // Check if placeholder mode is enabled via query parameter or environment variable
  // Default to true for testing/development (use placeholder if backend fails)
  const forcePlaceholder = query.usePlaceholder === 'true' || 
                            process.env.USE_PLACEHOLDER_PERMISSIONS === 'true';
  const disablePlaceholder = query.usePlaceholder === 'false';

  if (!roles && !groups) {
    throw createError({
      statusCode: 400,
      statusMessage: "roles or groups parameter is required",
    });
  }

  // Convert to arrays and handle single values
  const rolesArray = Array.isArray(roles) ? roles : roles ? [roles] : [];
  const groupsArray = Array.isArray(groups) ? groups : groups ? [groups] : [];

  // Extract primary role and group (use first one or combine)
  let primaryRole = rolesArray[0] || '';
  let primaryGroup = groupsArray[0] || '';
  
  // Normalize role and group
  primaryRole = normalizeRole(primaryRole);
  primaryGroup = normalizeGroup(primaryGroup);
  
  console.log(`📋 Normalized params - roles: ${primaryRole}, groups: ${primaryGroup}`);

  // Check for placeholder data first if placeholder mode is forced
  if (forcePlaceholder && !disablePlaceholder) {
    const placeholderData = getPlaceholderData(primaryRole, primaryGroup);
    if (placeholderData) {
      console.log(`📦 Using placeholder data (forced) for role: ${primaryRole}, group: ${primaryGroup}`);
      return placeholderData;
    }
    console.log(`⚠️ No placeholder data found for role: ${primaryRole}, group: ${primaryGroup}`);
  }

  // Build query parameters (use normalized values for API)
  const params = new URLSearchParams();
  if (primaryRole) params.append('roles', primaryRole);
  if (primaryGroup) params.append('groups', primaryGroup);

  // Backend API URL - adjust this to match your backend
  const backendUrl = `http://10.10.150.131:8089/api/v1/permission?${params.toString()}`;

  try {
    console.log(`📡 Fetching permissions from: ${backendUrl}`);
    console.log(`📋 Query params - roles: ${primaryRole}, groups: ${primaryGroup}`);
    
    const response = await $fetch(backendUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    });

    console.log("✅ Permission data fetched successfully");
    console.log("📦 Response structure:", {
      hasMessage: !!(response as any).message,
      hasData: !!(response as any).data,
      dataLength: Array.isArray((response as any).data) ? (response as any).data.length : 0,
      hasMeta: !!(response as any).meta,
    });
    
    // Log first permission item for debugging
    if ((response as any).data && Array.isArray((response as any).data) && (response as any).data.length > 0) {
      console.log("📄 Sample permission item:", (response as any).data[0]);
    }
    
    // Return the response as-is (it should have { message, data, meta } structure)
    return response;
  } catch (error: any) {
    console.error("❌ Error fetching permissions:", error);
    console.error("❌ Error details:", {
      message: error.message,
      status: error.status || error.statusCode,
      statusText: error.statusText || error.statusMessage,
      data: error.data,
    });
    
    // Fallback to placeholder data if available
    const placeholderData = getPlaceholderData(primaryRole, primaryGroup);
    if (placeholderData) {
      console.log(`📦 Falling back to placeholder data for role: ${primaryRole}, group: ${primaryGroup}`);
      return placeholderData;
    }
    
    // Return empty permissions structure if API fails and no placeholder available
    return {
      message: error.message || "Failed to fetch permissions",
      data: [],
      meta: {
        count: 0,
        total: 0
      }
    };
  }
});

