import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { MobileSessionService } from './mobile-session.service';
import { SKIP_MOBILE_SESSION_KEY } from './skip-mobile-session.decorator';

@Injectable()
export class MobileSessionGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly mobileSessionService: MobileSessionService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const skip = this.reflector.getAllAndOverride<boolean>(
      SKIP_MOBILE_SESSION_KEY,
      [context.getHandler(), context.getClass()],
    );
    if (skip) {
      return true;
    }

    const request = context.switchToHttp().getRequest();
    const user = await this.mobileSessionService.getUserFromRequest(request);
    this.mobileSessionService.assertSeekerUser(user);
    request.mobileUser = user;
    return true;
  }
}
