import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } 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 { parseWithAwait } from '@/server/utils/parseWithAwait';
import { FileService } from '@/server/modules/files/file.service';

const WechatLoginSchema = z.object({
  code: z.string().min(1).openapi({
    example: '0816TxlL1Qe3QY0qgDlL1pQxlL16TxlO',
    description: '微信授权code'
  })
});

const TokenResponseSchema = z.object({
  token: z.string().openapi({
    example: 'jwt.token.here',
    description: 'JWT Token'
  }),
  user: UserSchema.omit({ password: true })
})

const wechatLoginRoute = createRoute({
  method: 'post',
  path: '/login',
  request: {
    body: {
      content: {
        'application/json': {
          schema: WechatLoginSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '微信登录成功',
      content: {
        'application/json': {
          schema: TokenResponseSchema
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    401: {
      description: '微信认证失败',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono().openapi(wechatLoginRoute, async (c) => {
  try {
    const { code } = await c.req.json();

    const userService = new UserService(AppDataSource);
    const authService = new AuthService(userService);
    const fileService = new FileService(AppDataSource)

    const wechatAuthService = new WechatAuthService(userService, authService, fileService);
    const result = await wechatAuthService.wechatLogin(code);
    
    // 使用 parseWithAwait 确保返回数据符合Schema定义
    const validatedResult = await parseWithAwait(TokenResponseSchema, result);
    
    return c.json(validatedResult, 200);
  } catch (error) {
    return c.json({ 
      code: 401, 
      message: error instanceof Error ? error.message : '微信登录失败' 
    }, 401);
  }
});

export default app;