import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { MiniAuthService } from '../../../modules/auth/mini-auth.service';
import { AppDataSource } from '../../../data-source';
import { ErrorSchema } from '../../../utils/errorHandler';
import { UserEntity } from '../../../modules/users/user.entity';

const MiniLoginSchema = z.object({
  code: z.string().openapi({
    example: '08123456789012345678901234567890',
    description: '小程序登录code'
  }),
  userInfo: z.object({
    nickName: z.string().optional(),
    avatarUrl: z.string().optional()
  }).optional()
});

const MiniLoginResponseSchema = z.object({
  token: z.string().openapi({
    example: 'jwt.token.here',
    description: 'JWT Token'
  }),
  user: z.object({
    id: z.number(),
    username: z.string(),
    nickname: z.string().nullable(),
    phone: z.string().nullable(),
    email: z.string().nullable(),
    avatarFileId: z.number().nullable(),
    registrationSource: z.string()
  }),
  isNewUser: z.boolean().openapi({
    example: true,
    description: '是否为新注册用户'
  })
});

const miniLoginRoute = createRoute({
  method: 'post',
  path: '/mini-login',
  request: {
    body: {
      content: {
        'application/json': {
          schema: MiniLoginSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '小程序登录成功',
      content: {
        'application/json': {
          schema: MiniLoginResponseSchema
        }
      }
    },
    400: {
      description: '参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const miniAuthService = new MiniAuthService(AppDataSource);

const app = new OpenAPIHono().openapi(miniLoginRoute, async (c) => {
  try {
    const { code, userInfo } = c.req.valid('json');
    
    const result = await miniAuthService.miniLogin(code);
    
    // 如果有用户信息，更新用户资料
    if (userInfo) {
      await miniAuthService.updateUserProfile(result.user.id, {
        nickname: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl
      });
      
      // 重新获取更新后的用户信息
      const updatedUser = await AppDataSource.getRepository(UserEntity).findOne({
        where: { id: result.user.id },
        relations: ['avatarFile']
      });
      
      if (updatedUser) {
        result.user = updatedUser;
      }
    }
    
    return c.json({
      token: result.token,
      user: {
        id: result.user.id,
        username: result.user.username,
        nickname: result.user.nickname,
        phone: result.user.phone,
        email: result.user.email,
        avatarFileId: result.user.avatarFileId,
        registrationSource: result.user.registrationSource
      },
      isNewUser: result.isNewUser
    }, 200);
  } catch (error) {
    const { code = 500, message = '登录失败' } = error as Error & { code?: number };
    return c.json({ code, message }, 500);
  }
});

export default app;