/**
 * 账户模型
 * @file Account.js
 * @description 银行账户模型定义
 */
const { DataTypes } = require('sequelize');
const BaseModel = require('./BaseModel');
const { sequelize } = require('../config/database');

class Account extends BaseModel {
  /**
   * 获取账户余额（元）
   * @returns {String} 格式化后的余额
   */
  getBalanceFormatted() {
    return this.formatAmount(this.balance);
  }

  /**
   * 获取可用余额（元）
   * @returns {String} 格式化后的可用余额
   */
  getAvailableBalanceFormatted() {
    return this.formatAmount(this.available_balance);
  }

  /**
   * 获取冻结金额（元）
   * @returns {String} 格式化后的冻结金额
   */
  getFrozenAmountFormatted() {
    return this.formatAmount(this.frozen_amount);
  }

  /**
   * 检查账户是否可用
   * @returns {Boolean} 是否可用
   */
  isActive() {
    return this.status === 'active';
  }

  /**
   * 检查余额是否充足
   * @param {Number} amount 金额（分）
   * @returns {Boolean} 余额是否充足
   */
  hasSufficientBalance(amount) {
    return this.available_balance >= amount;
  }

  /**
   * 冻结资金
   * @param {Number} amount 金额（分）
   * @returns {Promise<Boolean>} 操作结果
   */
  async freezeAmount(amount) {
    if (!this.hasSufficientBalance(amount)) {
      return false;
    }
    
    this.available_balance -= amount;
    this.frozen_amount += amount;
    await this.save();
    return true;
  }

  /**
   * 解冻资金
   * @param {Number} amount 金额（分）
   * @returns {Promise<Boolean>} 操作结果
   */
  async unfreezeAmount(amount) {
    if (this.frozen_amount < amount) {
      return false;
    }
    
    this.available_balance += amount;
    this.frozen_amount -= amount;
    await this.save();
    return true;
  }

  /**
   * 扣减余额
   * @param {Number} amount 金额（分）
   * @returns {Promise<Boolean>} 操作结果
   */
  async deductBalance(amount) {
    if (!this.hasSufficientBalance(amount)) {
      return false;
    }
    
    this.balance -= amount;
    this.available_balance -= amount;
    await this.save();
    return true;
  }

  /**
   * 增加余额
   * @param {Number} amount 金额（分）
   * @returns {Promise<Boolean>} 操作结果
   */
  async addBalance(amount) {
    this.balance += amount;
    this.available_balance += amount;
    await this.save();
    return true;
  }

  /**
   * 获取账户交易记录
   * @param {Object} options 查询选项
   * @returns {Promise<Array>} 交易记录列表
   */
  async getTransactions(options = {}) {
    try {
      const { Transaction } = require('./index');
      return await Transaction.findAll({
        where: {
          account_id: this.id,
          ...options.where
        },
        order: [['created_at', 'DESC']],
        limit: options.limit || 50,
        ...options
      });
    } catch (error) {
      console.error('获取账户交易记录失败:', error);
      return [];
    }
  }
}

// 初始化Account模型
Account.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  account_number: {
    type: DataTypes.STRING(20),
    allowNull: false,
    unique: true,
    comment: '账户号码'
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'bank_users',
      key: 'id'
    }
  },
  account_type: {
    type: DataTypes.ENUM('savings', 'checking', 'credit', 'loan'),
    allowNull: false,
    defaultValue: 'savings',
    comment: '账户类型：储蓄、支票、信用卡、贷款'
  },
  balance: {
    type: DataTypes.BIGINT,
    allowNull: false,
    defaultValue: 0,
    comment: '账户余额（分）'
  },
  available_balance: {
    type: DataTypes.BIGINT,
    allowNull: false,
    defaultValue: 0,
    comment: '可用余额（分）'
  },
  frozen_amount: {
    type: DataTypes.BIGINT,
    allowNull: false,
    defaultValue: 0,
    comment: '冻结金额（分）'
  },
  currency: {
    type: DataTypes.STRING(3),
    allowNull: false,
    defaultValue: 'CNY',
    comment: '货币类型'
  },
  interest_rate: {
    type: DataTypes.DECIMAL(5, 4),
    allowNull: true,
    comment: '利率（年化）'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'frozen', 'closed'),
    allowNull: false,
    defaultValue: 'active'
  },
  opened_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: '开户时间'
  },
  closed_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '销户时间'
  },
  created_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  }
}, {
  sequelize,
  tableName: 'bank_accounts',
  modelName: 'Account'
});

module.exports = Account;