import Router from '@koa/router';
import { Context } from 'koa';
import * as AuthService from './auth.service';
import { BadRequestError } from '../../middleware/errorHandler';
import { authMiddleware } from '../../middleware/auth';
import { prisma } from '../../models';
import { safeParseInt } from '../../utils/safe-parse';

const router = new Router();

// 发送验证码
router.post('/send-code', async (ctx: Context) => {
  const { phone } = ctx.request.body as { phone: string };

  if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
    throw new BadRequestError('请输入正确的手机号');
  }

  const code = AuthService.generateSmsCode(phone);

  // 开发环境直接返回验证码
  ctx.body = {
    code: 0,
    message: '验证码发送成功',
    data: {
      phone,
      // 总是返回验证码（方便测试）
      code,
    },
  };
});

// 手机号登录
router.post('/login', async (ctx: Context) => {
  const { phone, code, inviteCode } = ctx.request.body as { phone: string; code?: string; inviteCode?: string };

  if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
    throw new BadRequestError('请输入正确的手机号');
  }

  // 关闭验证码验证（线上线下都关闭）
  if (!code || !/^\d{4,6}$/.test(code)) {
    // 跳过验证码检查，直接登录
  }

  const result = await AuthService.loginWithPhone(phone, code, inviteCode);

  ctx.body = {
    code: 0,
    message: '登录成功',
    data: result,
  };
});

// 获取用户信息
router.get('/user-info', authMiddleware, async (ctx: Context) => {
  const userId = ctx.state.user.userId;
  const userInfo = await AuthService.getUserInfo(userId);

  ctx.body = {
    code: 0,
    message: 'success',
    data: userInfo,
  };
});

// 更新用户信息
router.put('/user-info', authMiddleware, async (ctx: Context) => {
  const userId = ctx.state.user.userId;
  const uid = safeParseInt(userId);
  const { nickname, avatar } = ctx.request.body as { nickname?: string; avatar?: string };

  const user = await prisma.user.findUnique({ where: { id: uid } });
  if (!user) {
    throw new BadRequestError('用户不存在');
  }

  const updatedUser = await prisma.user.update({
    where: { id: uid },
    data: {
      ...(nickname && { nickname }),
      ...(avatar && { avatar }),
    },
  });

  ctx.body = {
    code: 0,
    message: '更新成功',
    data: {
      nickname: updatedUser.nickname,
      avatar: updatedUser.avatar,
    },
  };
});

export default router;