import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { MiniAuthService } from '../services/index.mt';
import { AppDataSource } from '@d8d/shared-utils';
import { ErrorSchema } from '@d8d/shared-utils';
import { UserEntityMt } from '@d8d/user-module-mt';
import { MiniLoginSchema, MiniLoginResponseSchema } from '../schemas/index.mt';


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 app = new OpenAPIHono().openapi(miniLoginRoute, async (c) => {
  try {
    // 在路由处理函数内部初始化服务
    const miniAuthService = new MiniAuthService(AppDataSource);

    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(UserEntityMt).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;