import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { AuthService } from '../services/index.mt';
import { UserServiceMt } from '@d8d/core-module-mt/user-module-mt';
import { ErrorSchema } from '@d8d/shared-utils';
import { AppDataSource } from '@d8d/shared-utils';


const routeDef = createRoute({
  method: 'get',
  path: '/sso-verify',
  responses: {
    200: {
      description: 'SSO验证成功',
      headers: {
        'X-Username': {
          schema: { type: 'string' },
          description: '格式化后的用户名'
        }
      }
    },
    401: {
      description: '未授权或令牌无效',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono().openapi(routeDef, async (c) => {
  try {
    // 在路由处理函数内部初始化服务
    const userService = new UserServiceMt(AppDataSource);
    const authService = new AuthService(userService);

    const token = c.req.header('Authorization')?.replace('Bearer ', '');

    if (!token) {
      return c.json({ code: 401, message: '未提供授权令牌' }, 401);
    }

    try {
      const userData = await authService.verifyToken(token);
      if (!userData) {
        return c.json({ code: 401, message: '无效令牌' }, 401);
      }

      return c.text('OK', 200);
    } catch (tokenError) {
      return c.json({ code: 401, message: '令牌验证失败' }, 401);
    }
  } catch (error) {
    return c.json({ code: 500, message: 'SSO验证失败' }, 500);
  }
});

export default app;