"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.usageLimitMiddleware = usageLimitMiddleware;
exports.checkWordLimit = checkWordLimit;
const models_1 = require("../models");
const errorHandler_1 = require("./errorHandler");
const types_1 = require("../types");
// 检查使用次数限制
async function usageLimitMiddleware(ctx, next) {
    const userId = ctx.state.user?.userId;
    // 测试模式：无需登录即可使用
    if (!userId) {
        ctx.state.userQuota = { dailyLimit: -1, wordLimit: -1 };
        await next();
        return;
    }
    const user = await models_1.prisma.user.findUnique({ where: { id: parseInt(userId) } });
    if (!user) {
        throw new errorHandler_1.ForbiddenError('用户不存在');
    }
    const today = new Date().toISOString().slice(0, 10);
    const memberLevel = user.memberLevel;
    const quota = types_1.MEMBER_QUOTA[memberLevel];
    // 重置每日使用次数
    if (user.lastUsageDate !== today) {
        await models_1.prisma.user.update({
            where: { id: parseInt(userId) },
            data: {
                dailyUsage: 0,
                lastUsageDate: today,
            },
        });
        user.dailyUsage = 0;
        user.lastUsageDate = today;
    }
    // 检查次数限制 (-1 表示无限制)
    if (quota.dailyLimit !== -1 && user.dailyUsage >= quota.dailyLimit) {
        throw new errorHandler_1.QuotaExceededError(`今日使用次数已达上限（${quota.dailyLimit}次），请升级会员`);
    }
    // 将用户信息和配额存入 state
    ctx.state.userQuota = quota;
    ctx.state.userInfo = user;
    await next();
}
// 检查字数限制
function checkWordLimit(wordCount) {
    return async (ctx, next) => {
        const quota = ctx.state.userQuota;
        if (!quota) {
            throw new errorHandler_1.ForbiddenError('请先检查使用限制');
        }
        // -1 表示无限制
        if (quota.wordLimit !== -1 && wordCount > quota.wordLimit) {
            throw new errorHandler_1.QuotaExceededError(`文本字数超出限制（${quota.wordLimit}字），请升级会员或缩短文本`);
        }
        await next();
    };
}
