"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const router_1 = __importDefault(require("@koa/router"));
const AuthService = __importStar(require("./auth.service"));
const errorHandler_1 = require("../../middleware/errorHandler");
const auth_1 = require("../../middleware/auth");
const models_1 = require("../../models");
const router = new router_1.default();
// 发送验证码
router.post('/send-code', async (ctx) => {
    const { phone } = ctx.request.body;
    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
        throw new errorHandler_1.BadRequestError('请输入正确的手机号');
    }
    const code = AuthService.generateSmsCode(phone);
    // 开发环境直接返回验证码
    ctx.body = {
        code: 0,
        message: '验证码发送成功',
        data: {
            phone,
            // 总是返回验证码（方便测试）
            code,
        },
    };
});
// 手机号登录
router.post('/login', async (ctx) => {
    const { phone, code } = ctx.request.body;
    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
        throw new errorHandler_1.BadRequestError('请输入正确的手机号');
    }
    // 开发环境免密登录：code为空或"123456"时直接登录
    const isDev = process.env.NODE_ENV === 'development';
    if (!isDev && (!code || !/^\d{4,6}$/.test(code))) {
        throw new errorHandler_1.BadRequestError('请输入正确的验证码');
    }
    const result = await AuthService.loginWithPhone(phone, code);
    ctx.body = {
        code: 0,
        message: '登录成功',
        data: result,
    };
});
// 获取用户信息
router.get('/user-info', auth_1.authMiddleware, async (ctx) => {
    const userId = ctx.state.user.userId;
    const userInfo = await AuthService.getUserInfo(userId);
    ctx.body = {
        code: 0,
        message: 'success',
        data: userInfo,
    };
});
// 更新用户信息
router.put('/user-info', auth_1.authMiddleware, async (ctx) => {
    const userId = ctx.state.user.userId;
    const { nickname, avatar } = ctx.request.body;
    const user = await models_1.prisma.user.findUnique({ where: { id: parseInt(userId) } });
    if (!user) {
        throw new errorHandler_1.BadRequestError('用户不存在');
    }
    const updatedUser = await models_1.prisma.user.update({
        where: { id: parseInt(userId) },
        data: {
            ...(nickname && { nickname }),
            ...(avatar && { avatar }),
        },
    });
    ctx.body = {
        code: 0,
        message: '更新成功',
        data: {
            nickname: updatedUser.nickname,
            avatar: updatedUser.avatar,
        },
    };
});
exports.default = router;
