import Provider from 'oidc-provider';
import type { Express } from 'express';
import type { Repository } from '../../db/repository.js';
import { buildA2aOidcConfig } from './oidc-config.js';
import { createConsentRouter } from './consent-api.js';
import { logger } from '../../logger.js';

export interface CreateA2aOidcDeps {
  repo: Repository;
  secretsDir: string;
  issuer: string;           // 例 https://maestro.example/oidc
  resourceAudience: string; // 例 https://maestro.example/a2a
  cookieKeys: string[];
}

export function createA2aOidcProvider(deps: CreateA2aOidcDeps): Provider {
  const config = buildA2aOidcConfig({
    repo: deps.repo,
    secretsDir: deps.secretsDir,
    resourceAudience: deps.resourceAudience,
    cookieKeys: deps.cookieKeys,
  });
  // oidc-provider の型は緩いので as any で渡す（構造的に互換）。
  const provider = new Provider(deps.issuer, config as any);
  // プロキシ配下（本番は逆プロキシ）。X-Forwarded-* を信頼。
  provider.proxy = true;
  return provider;
}

/** /oidc に provider、/oidc/interaction に consent を載せる。 */
export function mountA2aOidc(app: Express, provider: Provider, deps: { repo: Repository; resourceAudience: string }): void {
  // consent は provider.callback より前に置く（interaction パスを provider に食わせない）
  app.use('/oidc/interaction', createConsentRouter(provider, deps.repo, deps.resourceAudience));
  app.use('/oidc', provider.callback());
  logger.info('[a2a-oidc] mounted oidc provider at /oidc');
}
