/**
 * Impersonation Service
 * Allows admins to "Login as User" for support and debugging
 */

const jwt = require('jsonwebtoken');

class ImpersonationService {
  /**
   * Start impersonating a user
   * Admin logs in as a regular user while tracking the session
   */
  async startImpersonation(adminUser, targetUser) {
    try {
      console.log(`[Impersonation] Admin ${adminUser.userId} (${adminUser.email}) impersonating user ${targetUser.id} (${targetUser.email})`);

      // Generate a special JWT token with impersonation flag
      const impersonationToken = jwt.sign(
        {
          userId: targetUser.id,
          email: targetUser.email,
          role: targetUser.role || 'user',
          impersonating: true,
          impersonatorId: adminUser.userId,
          impersonatorEmail: adminUser.email,
          startedAt: new Date().toISOString()
        },
        process.env.JWT_SECRET,
        { expiresIn: '2h' } // Impersonation sessions are shorter
      );

      // Return impersonation data
      return {
        success: true,
        token: impersonationToken,
        impersonation: {
          targetUserId: targetUser.id,
          targetUserEmail: targetUser.email,
          targetUserName: `${targetUser.first_name} ${targetUser.last_name}`,
          adminUserId: adminUser.userId,
          adminUserEmail: adminUser.email,
          startedAt: new Date(),
          expiresAt: new Date(Date.now() + 2 * 60 * 60 * 1000) // 2 hours
        }
      };
    } catch (error) {
      console.error('[Impersonation] Error starting impersonation:', error.message);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * Check if a token is an impersonation token
   */
  isImpersonating(user) {
    return user && user.impersonating === true;
  }

  /**
   * Get impersonation details from token
   */
  getImpersonationDetails(user) {
    if (!this.isImpersonating(user)) {
      return null;
    }

    return {
      targetUserId: user.userId,
      targetUserEmail: user.email,
      adminUserId: user.impersonatorId,
      adminUserEmail: user.impersonatorEmail,
      startedAt: user.startedAt
    };
  }

  /**
   * Log impersonation activity to database
   */
  async logImpersonationActivity(pool, adminId, targetUserId, action, details = null) {
    try {
      const query = `
        INSERT INTO impersonation_logs (admin_id, target_user_id, action, details, created_at)
        VALUES (?, ?, ?, ?, NOW())
      `;

      await pool.execute(query, [
        adminId,
        targetUserId,
        action,
        details ? JSON.stringify(details) : null
      ]);

      console.log(`[Impersonation] Logged: ${action} by admin ${adminId} for user ${targetUserId}`);
    } catch (error) {
      console.error('[Impersonation] Error logging activity:', error.message);
    }
  }
}

module.exports = new ImpersonationService();
