import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi'
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';
import { AppDataSource } from '@/server/data-source';
import { AuthService } from '@/server/modules/auth/auth.service';
import { UserService } from '@/server/modules/users/user.service';
import { ErrorSchema } from '@/server/utils/errorHandler';

// 初始化服务
const userService = new UserService(AppDataSource);
const authService = new AuthService(userService);

const SuccessSchema = z.object({
  message: z.string().openapi({ example: '登出成功' })
})

// 定义路由
const routeDef = createRoute({
  method: 'post',
  path: '/logout',
  security: [{ Bearer: [] }],
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '登出成功',
      content: {
        'application/json': {
          schema: SuccessSchema
        }
      }
    },
    401: {
      description: '未授权',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const token = c.get('token');
    const decoded = authService.verifyToken(token);
    if (!decoded) {
      return c.json({ code: 401, message: '未授权' }, 401);
    }

    await authService.logout(token);
    return c.json({ message: '登出成功' }, 200);
  } catch (error) {
    console.error('登出失败:', error);
    return c.json({ code: 500, message: '登出失败' }, 500);
  }
});

export default app;