import { Request, Response } from 'express';
import { UserService } from '../services/user.service';
import { ResponseHandler } from '@utils/responseHandler';
import logger from '@utils/logger';

export class UserController {
  private userService: UserService;

  constructor() {
    this.userService = new UserService();
  }

  async searchUsers(req: Request, res: Response): Promise<void> {
    try {
      const q = String(req.query.q || '').trim();
      const limit = Number(req.query.limit || 10);
      const currentUserId = (req as any).user?.userId || (req as any).user?.id;

      const users = await this.userService.searchUsers(q, limit, currentUserId);

      const result = users.map(u => ({
        userId: (u as any).userId,
        email: (u as any).email,
        displayName: (u as any).displayName,
        firstName: (u as any).firstName,
        lastName: (u as any).lastName,
        department: (u as any).department,
        designation: (u as any).designation,
        isActive: (u as any).isActive,
      }));

      ResponseHandler.success(res, result, 'Users fetched');
    } catch (error) {
      logger.error('User search failed', { error });
      ResponseHandler.error(res, 'User search failed', 500);
    }
  }

  /**
   * Ensure user exists in database (create if not exists)
   * Called when user is selected/tagged in the frontend
   */
  async ensureUserExists(req: Request, res: Response): Promise<void> {
    try {
      const { userId, email, displayName, firstName, lastName, department, phone } = req.body;

      if (!userId || !email) {
        ResponseHandler.error(res, 'userId and email are required', 400);
        return;
      }

      const user = await this.userService.ensureUserExists({
        userId,
        email,
        displayName,
        firstName,
        lastName,
        department,
        phone
      });

      ResponseHandler.success(res, {
        userId: user.userId,
        email: user.email,
        displayName: user.displayName,
        firstName: user.firstName,
        lastName: user.lastName,
        department: user.department,
        isActive: user.isActive
      }, 'User ensured in database');
    } catch (error: any) {
      logger.error('Ensure user failed', { error });
      ResponseHandler.error(res, error.message || 'Failed to ensure user', 500);
    }
  }
}


