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';

const AuthorizeSchema = z.object({
  redirectUri: z.string().url().openapi({
    example: 'https://example.com/auth/callback',
    description: '回调地址'
  }),
  scope: z.enum(['snsapi_base', 'snsapi_userinfo']).default('snsapi_userinfo').openapi({
    example: 'snsapi_userinfo',
    description: '授权范围'
  })
});

const AuthorizeResponseSchema = z.object({
  url: z.string().url().openapi({
    example: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx',
    description: '微信授权URL'
  })
});

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

const authorizeRoute = createRoute({
  method: 'post',
  path: '/authorize',
  request: {
    body: {
      content: {
        'application/json': {
          schema: AuthorizeSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '获取微信授权URL成功',
      content: {
        'application/json': {
          schema: AuthorizeResponseSchema
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono().openapi(authorizeRoute, async (c) => {
  try {
    const { redirectUri, scope } = await c.req.json();
    const url = wechatAuthService.getAuthorizationUrl(redirectUri, scope);
    return c.json({ url }, 200);
  } catch (error) {
    return c.json({ 
      code: 400, 
      message: error instanceof Error ? error.message : '获取授权URL失败' 
    }, 400);
  }
});

export default app;