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

const userService = new UserService(AppDataSource);
const authService = new AuthService(userService);
const wechatAuthService = new WechatAuthService(userService, authService);

const unbindWechatRoute = createRoute({
  method: 'post',
  path: '/unbind',
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '解绑微信账号成功',
      content: {
        'application/json': {
          schema: UserSchema
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    401: {
      description: '认证失败',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(unbindWechatRoute, async (c) => {
  try {
    const user = c.get('user');
    const result = await wechatAuthService.unbindWechatFromUser(user.id);
    
    // 使用 parseWithAwait 确保返回数据符合Schema定义
    const validatedResult = await parseWithAwait(UserSchema, result);
    
    return c.json(validatedResult, 200);
  } catch (error) {
    return c.json({ 
      code: 400, 
      message: error instanceof Error ? error.message : '解绑微信账号失败' 
    }, 400);
  }
});

export default app;