import type { Request } from 'express';
import { UnauthenticatedUser, type User } from '@a2a-js/sdk/server';
import type Provider from 'oidc-provider';
import type { Repository } from '../../db/repository.js';
import { authenticateA2aRequest, type A2aPrincipal } from './token-auth.js';

/** Authenticated A2A user carrying the resolved delegation principal. */
export class A2aAuthenticatedUser implements User {
  constructor(public readonly a2aPrincipal: A2aPrincipal) {}
  get isAuthenticated(): boolean { return true; }
  get userName(): string { return this.a2aPrincipal.actingUserId; }
}

export type A2aUserBuilder = (req: Request) => Promise<User>;

export function makeA2aUserBuilder(provider: Provider, repo: Repository): A2aUserBuilder {
  return async (req: Request): Promise<User> => {
    const principal = await authenticateA2aRequest(provider, repo, req, new Date().toISOString());
    if (!principal) return new UnauthenticatedUser();
    return new A2aAuthenticatedUser(principal);
  };
}
