import { Request, Response } from 'express';

import { getErrorMessage } from '../../utils/error-utils';

import { sessionService } from './session.service';

/**
 * EN: Sessions Controller
 * VI: Controller sessions
 */
export class SessionsController {
  /**
   * EN: Get user sessions
   * VI: Lấy sessions của người dùng
   */
  async getUserSessions(req: Request, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.id || (req as any).user?.sub;
      
      if (!userId) {
        res.status(401).json({
          success: false,
          error: { code: 'UNAUTHORIZED', message: 'Authentication required' },
        });
        return;
      }

      const sessions = await sessionService.getUserSessions(userId);

      res.json({
        success: true,
        data: sessions.map(s => ({
          id: s.id,
          deviceName: s.deviceName,
          ipAddress: s.ipAddress,
          lastActivityAt: s.lastActivityAt,
          createdAt: s.createdAt,
          expiresAt: s.expiresAt,
        })),
      });
    } catch (error: unknown) {
      res.status(500).json({
        success: false,
        error: {
          code: 'GET_SESSIONS_FAILED',
          message: getErrorMessage(error) || 'Failed to get sessions',
        },
      });
    }
  }

  /**
   * EN: Revoke session
   * VI: Thu hồi session
   */
  async revokeSession(req: Request, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.id || (req as any).user?.sub;
      const { sessionId } = req.params;

      if (!userId) {
        res.status(401).json({
          success: false,
          error: { code: 'UNAUTHORIZED', message: 'Authentication required' },
        });
        return;
      }

      await sessionService.revokeSession(sessionId);

      res.json({
        success: true,
        data: { message: 'Session revoked successfully' },
      });
    } catch (error: unknown) {
      res.status(500).json({
        success: false,
        error: {
          code: 'REVOKE_SESSION_FAILED',
          message: getErrorMessage(error) || 'Failed to revoke session',
        },
      });
    }
  }

  /**
   * EN: Revoke all sessions
   * VI: Thu hồi tất cả sessions
   */
  async revokeAllSessions(req: Request, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.id || (req as any).user?.sub;

      if (!userId) {
        res.status(401).json({
          success: false,
          error: { code: 'UNAUTHORIZED', message: 'Authentication required' },
        });
        return;
      }

      await sessionService.revokeAllUserSessions(userId);

      res.json({
        success: true,
        data: { message: 'All sessions revoked successfully' },
      });
    } catch (error: unknown) {
      res.status(500).json({
        success: false,
        error: {
          code: 'REVOKE_ALL_SESSIONS_FAILED',
          message: getErrorMessage(error) || 'Failed to revoke all sessions',
        },
      });
    }
  }
}

export const sessionsController = new SessionsController();
