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';

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 } = ctx.request.body as { phone: string; code?: string };

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

  // 开发环境免密登录：code为空或"123456"时直接登录
  const isDev = process.env.NODE_ENV === 'development';
  if (!isDev && (!code || !/^\d{4,6}$/.test(code))) {
    throw new BadRequestError('请输入正确的验证码');
  }

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

  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 { nickname, avatar } = ctx.request.body as { nickname?: string; avatar?: string };

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

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

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

export default router;