import type { Request, Response } from 'express';
import logger from '@/shared/logger';
import SearchService from '@/services/search';

export async function search(req: Request, res: Response): Promise<void> {
  const { searchQuery, organizationId } = req.body;
  const globalAccess = req.currentUser?.app_role?.globalAccess ?? false;

  if (!searchQuery) {
    res.status(400).json({ error: 'Please enter a search query' });
    return;
  }

  try {
    const foundMatches = await SearchService.search(
      searchQuery,
      req.currentUser,
      organizationId,
      globalAccess,
    );
    res.json(foundMatches);
  } catch (error) {
    logger.error('Internal Server Error', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}
