"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateSmsCode = generateSmsCode;
exports.verifySmsCode = verifySmsCode;
exports.generateToken = generateToken;
exports.loginWithPhone = loginWithPhone;
exports.getUserInfo = getUserInfo;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const models_1 = require("../../models");
// 验证码存储（生产环境应使用 Redis）
const smsCodes = new Map();
// 生成验证码
function generateSmsCode(phone) {
    const code = Math.random().toString().slice(2, 6);
    smsCodes.set(phone, {
        code,
        expireAt: Date.now() + 5 * 60 * 1000, // 5分钟有效
    });
    console.log(`📱 验证码已生成: ${phone} -> ${code}`);
    return code;
}
// 验证验证码
function verifySmsCode(phone, code) {
    const stored = smsCodes.get(phone);
    if (!stored)
        return false;
    if (Date.now() > stored.expireAt) {
        smsCodes.delete(phone);
        return false;
    }
    if (stored.code !== code)
        return false;
    smsCodes.delete(phone);
    return true;
}
// 生成 JWT Token
function generateToken(userId, phone) {
    const secret = 'my-jwt-secret-key-2024';
    const payload = { userId, phone };
    return jsonwebtoken_1.default.sign(payload, secret, {
        expiresIn: '7d',
    });
}
// 手机号登录/注册
async function loginWithPhone(phone, code) {
    // 免密登录：开发环境下，code 为空或为"123456"时直接登录
    const isDev = process.env.NODE_ENV === 'development';
    const skipVerify = isDev && (!code || code === '123456');
    if (!skipVerify) {
        // 验证验证码
        const isValid = verifySmsCode(phone, code || '');
        if (!isValid) {
            throw new Error('验证码错误或已过期');
        }
    }
    // 查找或创建用户
    let user = await models_1.prisma.user.findFirst({ where: { phone } });
    let isNewUser = false;
    if (!user) {
        user = await models_1.prisma.user.create({
            data: {
                phone,
                nickname: `用户${phone.slice(-4)}`,
                avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${phone}`,
                memberLevel: 0,
                dailyUsage: 0,
                lastUsageDate: '',
            },
        });
        isNewUser = true;
    }
    const token = generateToken(user.id.toString(), phone);
    return {
        token,
        user: {
            id: user.id.toString(),
            phone: user.phone,
            nickname: user.nickname,
            avatar: user.avatar,
            memberLevel: user.memberLevel,
            isNewUser,
        },
    };
}
// 获取用户信息
async function getUserInfo(userId) {
    const user = await models_1.prisma.user.findUnique({ where: { id: parseInt(userId) } });
    if (!user) {
        throw new Error('用户不存在');
    }
    return {
        id: user.id.toString(),
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar,
        memberLevel: user.memberLevel,
        memberExpireAt: user.memberExpireAt,
        dailyUsage: user.dailyUsage,
    };
}
