import { Request, Response } from 'express';
import userService from '../services/user.service';
import logger from '../utils/logger';

class UserController {
  /**
   * Get current user
   * GET /api/user/me
   */
  async getCurrentUser(req: Request, res: Response): Promise<void> {
    try {
      // User is attached by auth middleware
      if (!req.user) {
        res.status(401).json({
          success: false,
          message: 'Not authenticated',
        });
        return;
      }

      // Get full user details from database
      const user = await userService.findById(req.user.id);

      if (!user) {
        logger.warn('Authenticated user not found in database', {
          userId: req.user.id,
        });
        res.status(404).json({
          success: false,
          message: 'User not found',
        });
        return;
      }

      logger.debug('Fetched current user', { userId: user.id });

      res.status(200).json({
        success: true,
        data: {
          id: user.id,
          email: user.email,
          name: user.name,
          preferredUsername: user.preferred_username,
          givenName: user.given_name,
          familyName: user.family_name,
          profilePictureUrl: user.profile_picture_url,
          isActive: user.is_active,
          lastLoginAt: user.last_login_at,
          createdAt: user.created_at,
        },
      });
    } catch (error) {
      logger.error('Get current user error', { error });

      res.status(500).json({
        success: false,
        message: 'Failed to fetch user information',
      });
    }
  }
}

export default new UserController();
