import { Hono } from 'hono';
import type { Context, Next } from 'hono';
import { OIDCProvider } from '../provider';
import type { OIDCProviderConfig } from '../types';

/**
 * 创建OIDC Provider Hono应用
 */
export function createOIDCProvider(config: OIDCProviderConfig): Hono {
    const app = new Hono();
    const provider = new OIDCProvider(config);

    // 登录端点
    app.post('/login', async (c: Context) => {
        return await provider.handleLogin(c);
    });

    // 登出端点
    app.get('/logout', async (c: Context) => {
        return await provider.handleLogout(c);
    });

    app.post('/logout', async (c: Context) => {
        return await provider.handleLogout(c);
    });

    // 发现文档端点 - 直接调用核心方法
    app.get('/.well-known/openid-configuration', (c: Context) => {
        return c.json(provider.getDiscoveryDocument());
    });

    // JWKS端点 - 直接调用核心方法
    app.get('/.well-known/jwks.json', async (c: Context) => {
        return c.json(await provider.getJWKS());
    });

    // 授权端点
    app.get('/auth', async (c: Context) => {
        return await provider.handleAuthorization(c);
    });

    // 令牌端点
    app.post('/token', async (c: Context) => {
        return await provider.handleToken(c);
    });

    // 用户信息端点
    app.get('/userinfo', async (c: Context) => {
        return await provider.handleUserInfo(c);
    });

    // 令牌撤销端点
    app.post('/revoke', async (c: Context) => {
        return await provider.handleRevoke(c);
    });

    // 令牌内省端点
    app.post('/introspect', async (c: Context) => {
        return await provider.handleIntrospect(c);
    });

    // 返回应用实例
    return app;
}

/**
 * OIDC Provider中间件
 */
export function oidcProvider(config: OIDCProviderConfig) {
    const provider = new OIDCProvider(config);

    return (c: Context, next: Next) => {
        c.set('oidc:provider', provider);
        return next();
    };
}

/**
 * 获取OIDC Provider实例
 */
export function getOIDCProvider(c: Context): OIDCProvider {
    return c.get('oidc:provider');
}

