import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { MiniAuthService } from '../services';
import { AppDataSource, redisUtil } from '@d8d/shared-utils';
import { ErrorSchema } from '@d8d/shared-utils';
import { UserEntity } from '@d8d/user-module';
import { authMiddleware } from '../middleware';
import { AuthContext } from '@d8d/shared-types';
import { PhoneDecryptSchema, PhoneDecryptResponseSchema } from '../schemas';

const phoneDecryptRoute = createRoute({
  method: 'post',
  path: '/phone-decrypt',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': {
          schema: PhoneDecryptSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '手机号解密成功',
      content: {
        'application/json': {
          schema: PhoneDecryptResponseSchema
        }
      }
    },
    400: {
      description: '参数错误或解密失败',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    401: {
      description: '未授权访问',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    404: {
      description: '用户不存在',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(phoneDecryptRoute, async (c) => {
  try {
    const { encryptedData, iv } = c.req.valid('json');
    const user = c.get('user');

    if (!user) {
      return c.json({ code: 401, message: '未授权访问' }, 401);
    }

    // 获取用户信息
    const userRepository = AppDataSource.getRepository(UserEntity);
    const userEntity = await userRepository.findOne({
      where: { id: user.id },
      relations: ['avatarFile']
    });

    if (!userEntity) {
      return c.json({ code: 404, message: '用户不存在' }, 404);
    }

    // 创建 MiniAuthService 实例
    const miniAuthService = new MiniAuthService(AppDataSource);

    // 从Redis获取用户的sessionKey
    const sessionKey = await redisUtil.getSessionKey(user.id);

    if (!sessionKey) {
      return c.json({ code: 400, message: 'sessionKey已过期，请重新登录' }, 400);
    }

    // 使用 MiniAuthService 进行手机号解密
    const decryptedPhoneNumber = await miniAuthService.decryptPhoneNumber(
      encryptedData,
      iv,
      sessionKey
    );

    // 更新用户手机号
    userEntity.phone = decryptedPhoneNumber;
    await userRepository.save(userEntity);

    return c.json({
      phoneNumber: decryptedPhoneNumber,
      user: {
        id: userEntity.id,
        username: userEntity.username,
        nickname: userEntity.nickname,
        phone: userEntity.phone,
        email: userEntity.email,
        avatarFileId: userEntity.avatarFileId,
        registrationSource: userEntity.registrationSource
      }
    }, 200);
  } catch (error) {
    const { code = 500, message = '手机号解密失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code as 400 | 401 | 404 | 500);
  }
});

export default app;