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

type AuthenticatedRequest = {
  user?: { userId: string; role?: string | undefined; primaryDriverId?: string | undefined };
};

@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) {
      console.log(`[AuthenticationGuard] Session found for user: ${session.user.id}, primaryDriverId: ${session.user.primaryDriverId}`);
      request.user = { 
        userId: session.user.id,
        role: session.user.role,
        primaryDriverId: session.user.primaryDriverId
      };
    }

    return true;
  }
}