/**
 * 支付日志（清晰重构版）
 * 由 省胜优铺 从逆向版重写，功能等价
 */
const { run, get, all } = require('../../utils/db');

function ensureTable() {
  run(`CREATE TABLE IF NOT EXISTS payment_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    trade_no TEXT NOT NULL,
    action TEXT NOT NULL,
    channel TEXT DEFAULT '',
    message TEXT DEFAULT '',
    request_data TEXT DEFAULT '',
    response_data TEXT DEFAULT '',
    level TEXT DEFAULT 'info',
    created_at DATETIME DEFAULT (datetime('now','localtime'))
  )`);
}

/**
 * 记录支付日志
 * @param {string} tradeNo 业务单号
 * @param {string} action  动作（create_payment/notify/refund...）
 * @param {string} message 描述
 * @param {object} opts    附加 {channel, requestData, responseData, level}
 */
function log(tradeNo, action, message = '', opts = {}) {
  const { channel = '', requestData = '', responseData = '', level = 'info' } = opts;
  try {
    ensureTable();
    run(
      'INSERT INTO payment_logs(trade_no, action, channel, message, request_data, response_data, level) VALUES(?,?,?,?,?,?,?)',
      [tradeNo || '', action, channel, message, requestData, responseData, level]
    );
    const icon = level === 'error' ? '❌' : level === 'warn' ? '⚠️' : '✅';
    console.log(`[支付${icon}] [${channel}] ${action}: ${message}`.slice(0, 1200));
  } catch (e) {
    console.error('[支付日志] 写入日志失败:', e.message);
  }
}

/** 查询日志（可按单号） */
function queryLogs(tradeNo = '', limit = 100) {
  try {
    ensureTable();
    if (tradeNo) {
      return all('SELECT * FROM payment_logs WHERE trade_no=? ORDER BY id DESC LIMIT ?', [tradeNo, limit]);
    }
    return all('SELECT * FROM payment_logs ORDER BY id DESC LIMIT ?', [limit]);
  } catch (e) {
    console.error('[支付日志] 查询失败:', e.message);
    return [];
  }
}

module.exports = { log, queryLogs };
