import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
import type { IdentitySessionPort } from '@core/identity/application/ports/IdentitySessionPort';
import { IDENTITY_SESSION_PORT_TOKEN } from './AuthProviders';

type AuthenticatedRequest = {
  user?: { userId: string };
};

@Injectable()
export class AuthenticationGuard implements CanActivate {
  constructor(
    @Inject(IDENTITY_SESSION_PORT_TOKEN)
    private readonly sessionPort: IdentitySessionPort,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<AuthenticatedRequest>();

    if (request.user?.userId) {
      return true;
    }

    const session = await this.sessionPort.getCurrentSession();
    if (session?.user?.id) {
      request.user = { userId: session.user.id };
    }

    return true;
  }
}