const coinRebateCode = "daily_coin_rebate";
const onlineNoticeCode = "online_global_notice";

export function readVipBenefitMetadata(metadataJson) {
    try {
        const metadata = JSON.parse(String(metadataJson || "{}").trim() || "{}");
        return metadata && !Array.isArray(metadata) && typeof metadata === "object" ? metadata : null;
    } catch {
        return null;
    }
}

export function vipBenefitMetadataField(metadataJson, field) {
    const metadata = readVipBenefitMetadata(metadataJson);
    const value = metadata?.[field];
    return value === undefined || value === null ? "" : String(value);
}

export function updateVipBenefitMetadataField(metadataJson, field, value) {
    const metadata = readVipBenefitMetadata(metadataJson);
    if (!metadata) {
        // 原始 JSON 非法时不能擅自覆盖并丢失其它字段；运营需先在元数据框修正 JSON，再使用结构化字段。
        return String(metadataJson || "{}");
    }
    const next = { ...metadata };
    if (value === "" || value === undefined || value === null) {
        delete next[field];
    } else {
        next[field] = value;
    }
    return JSON.stringify(next);
}

export function normalizeVipBenefitMetadata({ benefitCode, label, metadataJson, status }) {
    const metadata = readVipBenefitMetadata(metadataJson);
    if (!metadata) {
        // 调用方会先给出统一的“必须是 JSON 对象”错误；这里保留防御，避免未来绕过表单校验。
        throw new Error(`${label} 元数据必须是 JSON 对象`);
    }
    if (benefitCode === coinRebateCode) {
        normalizeCoinAmount(metadata, label, status);
    }
    if (benefitCode === onlineNoticeCode) {
        normalizeNoticeMessage(metadata, label);
    }
    return benefitCode === coinRebateCode || benefitCode === onlineNoticeCode
        ? JSON.stringify(metadata)
        : String(metadataJson || "{}").trim() || "{}";
}

function normalizeCoinAmount(metadata, label, status) {
    const rawAmount = metadata.coin_amount;
    const hasAmount = rawAmount !== undefined && rawAmount !== null && rawAmount !== "";
    if (!hasAmount) {
        delete metadata.coin_amount;
        if (status === "active") {
            throw new Error(`${label} 启用时每日返现金币必须为正整数`);
        }
        return;
    }
    const amount = Number(rawAmount);
    if (!Number.isSafeInteger(amount) || amount <= 0) {
        throw new Error(`${label} 每日返现金币必须为正整数`);
    }
    // 后端消费固定使用 JSON number；兼容读取历史字符串后在保存时收敛类型。
    metadata.coin_amount = amount;
}

function normalizeNoticeMessage(metadata, label) {
    const message = String(metadata.message ?? "").trim();
    if (!message) {
        delete metadata.message;
        return;
    }
    if (message.length > 256) {
        throw new Error(`${label} 上线飘屏文案不能超过 256 个字符`);
    }
    metadata.message = message;
}
