import { JwksService } from '@frontmcp/auth';

import { FrontMcpAuth, ProviderScope, type ScopeEntry, type ServerRequest } from '../../common';
import { type TransparentAuthOptions } from '../../common/types/options/auth';
import type ProviderRegistry from '../../provider/provider.registry';
import SessionVerifyFlow from '../flows/session.verify.flow';
import WellKnownJwksFlow from '../flows/well-known.jwks.flow';
import WellKnownAsFlow from '../flows/well-known.oauth-authorization-server.flow';
import WellKnownPrmFlow from '../flows/well-known.prm.flow';

export class RemotePrimaryAuth extends FrontMcpAuth<TransparentAuthOptions> {
  override ready: Promise<void>;
  private jwks = new JwksService();

  constructor(
    private readonly scope: ScopeEntry,
    private readonly providers: ProviderRegistry,
    options: TransparentAuthOptions,
  ) {
    super(options);
    this.ready = this.initialize();
  }

  override fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
    return fetch(input, init);
  }

  override validate(request: ServerRequest): Promise<void> {
    return Promise.resolve();
  }

  get issuer(): string {
    return this.options.provider;
  }

  protected async initialize() {
    const scope = this.providers.getActiveScope();

    this.providers.injectProvider({
      value: this.jwks,
      metadata: {
        scope: ProviderScope.GLOBAL,
        name: 'auth:jwk-service',
      },
      provide: JwksService,
    });

    await this.registerAuthFlows(scope);
    return Promise.resolve();
  }

  private async registerAuthFlows(scope: ScopeEntry) {
    await scope.registryFlows(
      WellKnownPrmFlow /** /.well-known/oauth-protected-resource */,
      WellKnownAsFlow /** /.well-known/oauth-authorization-server */,
      WellKnownJwksFlow /** /.well-known/jwks.json */,
      SessionVerifyFlow /** Session verification flow */,
    );
  }
}
