import { apiService, Application, PaginatedResponse } from '../services/apiService';

interface SearchResult {
  id: string;
  title: string;
  description?: string;
  appId: string;
  action?: () => void;
}

export const kmsSearchProvider = async (query: string): Promise<SearchResult[]> => {
  const results: SearchResult[] = [];

  try {
    // Search applications
    const applicationsResponse: PaginatedResponse<Application> = await apiService.getApplications();
    applicationsResponse.data
      .filter((app: Application) => 
        app.app_id.toLowerCase().includes(query.toLowerCase()) ||
        (app.owner?.name && app.owner.name.toLowerCase().includes(query.toLowerCase()))
      )
      .forEach((app: Application) => {
        results.push({
          id: `app-${app.app_id}`,
          title: app.app_id,
          description: `Application owned by ${app.owner?.name || 'Unknown'}`,
          appId: 'KMS',
          action: () => {
            window.location.hash = '/kms/applications';
          }
        });
      });

    // Add quick actions
    const quickActions = [
      { key: 'applications', title: 'Applications', path: '/kms/applications' },
      { key: 'tokens', title: 'Tokens', path: '/kms/tokens' },
      { key: 'users', title: 'Users', path: '/kms/users' },
      { key: 'audit', title: 'Audit Log', path: '/kms/audit' },
      { key: 'dashboard', title: 'Dashboard', path: '/kms' },
    ];

    quickActions
      .filter(action => action.title.toLowerCase().includes(query.toLowerCase()))
      .forEach(action => {
        results.push({
          id: `quick-${action.key}`,
          title: action.title,
          description: `Navigate to ${action.title}`,
          appId: 'KMS',
          action: () => {
            window.location.hash = action.path;
          }
        });
      });

  } catch (error) {
    console.error('KMS search error:', error);
  }

  return results.slice(0, 10); // Limit results
};

export default kmsSearchProvider;