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

const PhoneDecryptSchema = z.object({
  encryptedData: z.string().openapi({
    example: 'encrypted_phone_data_here',
    description: '微信小程序加密的手机号数据'
  }),
  iv: z.string().openapi({
    example: 'encryption_iv_here',
    description: '加密算法的初始向量'
  })
});

const PhoneDecryptResponseSchema = z.object({
  phoneNumber: z.string().openapi({
    example: '13800138000',
    description: '解密后的手机号'
  }),
  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()
  })
});

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;