import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; import { WsException } from '@nestjs/websockets'; import { Socket } from 'socket.io'; import { BusinessHoursService } from '../business-hours.service'; import { createSocketResponse } from 'src/socket/support-management/dto/eventPayloads.dto'; import { HttpStatus } from '@nestjs/common'; @Injectable() export class BusinessHoursGuard implements CanActivate { constructor(private readonly businessHoursService: BusinessHoursService) {} async canActivate(context: ExecutionContext): Promise { const client = context.switchToWs().getClient(); const status = await this.businessHoursService.isOpen(); const nextOpen = await this.businessHoursService.getNextOpen(); if (!status.open) { const message = status.reason || 'Online conversation is not available now. Please try again later.'; const errorResponse = createSocketResponse( 'ONLINE_CONVERSATION_DISABLED', { code: 'ONLINE_CONVERSATION_DISABLED', message, nextOpen: nextOpen?.toISOString() || null, }, message, HttpStatus.SERVICE_UNAVAILABLE, ); client.emit('response', errorResponse); throw new WsException({ code: 'ONLINE_CONVERSATION_DISABLED', message, nextOpen: nextOpen?.toISOString() || null, }); } return true; } }