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

/** Resolves seeker from session when token is sent; allows guest requests without a token. */
@Injectable()
export class MobileOptionalSessionGuard implements CanActivate {
  constructor(private readonly mobileSessionService: MobileSessionService) { }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = this.mobileSessionService.extractSessionToken(request);

    if (!token) {
      request.mobileUser = null;
      return true;
    }

    try {
      const user = await this.mobileSessionService.getUserFromSessionToken(token);
      this.mobileSessionService.assertSeekerUser(user);
      request.mobileUser = user;
    } catch (err) {
      // If the session token is invalid, expired, or doesn't belong to a seeker, fall back to guest mode.
      request.mobileUser = null;
    }
    return true;
  }
}