import { JwtService } from '@nestjs/jwt';
import { firstValueFrom } from 'rxjs';
import { CoreGrpcService } from '../core-grpc.service';
import { FedcmSessionPayload, resolveFedcmSessionFromRequest } from './fedcm-cookie';

export async function resolveFedcmSessionPinState(
  jwt: JwtService,
  core: CoreGrpcService,
  cookieHeader?: string
): Promise<{ session: FedcmSessionPayload | null; requiresPin: boolean }> {
  const session = await resolveFedcmSessionFromRequest(jwt, cookieHeader);
  if (!session) {
    return { session: null, requiresPin: false };
  }

  const validation = (await firstValueFrom(
    core.auth.ValidateSession({
      userId: session.sub,
      sessionId: session.sessionId,
      touchActivity: false
    })
  )) as { requiresPin: boolean; pinVerified?: boolean };

  const requiresPin = Boolean(validation.requiresPin || !session.pinVerified);
  return { session, requiresPin };
}
