/**
 * 账号工具函数
 * 提供账号相关的工具方法
 */

const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');

// 启用 UTC 和时区插件
dayjs.extend(utc);
dayjs.extend(timezone);

/**
 * 计算剩余天数（使用 UTC 时间避免时区问题）
 * @param {Date|string|null} authorizationDate - 授权日期
 * @param {number} authorizationDays - 授权天数
 * @returns {number} 剩余天数
 */
function calculateRemainingDays(authorizationDate, authorizationDays) {
  if (!authorizationDate || !authorizationDays || authorizationDays <= 0) {
    return 0;
  }

  // 使用 UTC 时间计算，避免时区问题
  const startDate = dayjs(authorizationDate).utc().startOf('day');
  const endDate = startDate.add(authorizationDays, 'day');
  const now = dayjs().utc().startOf('day');

  // 计算剩余天数
  const remaining = endDate.diff(now, 'day', false); // 使用整数天数
  return Math.max(0, remaining);
}

/**
 * 检查授权是否有效
 * @param {Date|string|null} authorizationDate - 授权日期
 * @param {number} authorizationDays - 授权天数
 * @returns {boolean} 授权是否有效
 */
function isAuthorizationValid(authorizationDate, authorizationDays) {
  const remainingDays = calculateRemainingDays(authorizationDate, authorizationDays);
  return remainingDays > 0;
}

/**
 * 为账号对象添加 remaining_days 字段
 * @param {Object} account - 账号对象（可以是 Sequelize 实例或普通对象）
 * @returns {Object} 添加了 remaining_days 的账号对象
 */
function addRemainingDays(account) {
  // 如果是 Sequelize 实例，转换为普通对象
  const accountData = account.toJSON ? account.toJSON() : account;
  
  const authDate = accountData.authorization_date;
  const authDays = accountData.authorization_days || 0;
  
  accountData.remaining_days = calculateRemainingDays(authDate, authDays);
  
  return accountData;
}

/**
 * 为账号数组添加 remaining_days 字段
 * @param {Array} accounts - 账号数组
 * @returns {Array} 添加了 remaining_days 的账号数组
 */
function addRemainingDaysToAccounts(accounts) {
  if (!Array.isArray(accounts)) {
    return accounts;
  }
  
  return accounts.map(account => addRemainingDays(account));
}

module.exports = {
  calculateRemainingDays,
  isAuthorizationValid,
  addRemainingDays,
  addRemainingDaysToAccounts
};

