/**
 * 贷款合同模型
 * @file LoanContract.js
 * @description 银行系统贷款合同数据模型
 */
const { DataTypes } = require('sequelize');
const BaseModel = require('./BaseModel');

class LoanContract extends BaseModel {
  /**
   * 获取合同状态文本
   * @returns {String} 状态文本
   */
  getStatusText() {
    const statusMap = {
      active: '已放款',
      completed: '已完成',
      defaulted: '违约',
      cancelled: '已取消'
    };
    return statusMap[this.status] || this.status;
  }

  /**
   * 格式化合同金额
   * @returns {String} 格式化后的金额
   */
  getFormattedAmount() {
    return `${this.loan_amount.toFixed(2)}元`;
  }
}

// 初始化LoanContract模型
LoanContract.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  contract_number: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    comment: '合同编号'
  },
  customer_name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: '客户姓名'
  },
  customer_phone: {
    type: DataTypes.STRING(20),
    allowNull: false,
    comment: '客户电话'
  },
  customer_id_card: {
    type: DataTypes.STRING(18),
    allowNull: false,
    comment: '客户身份证号'
  },
  loan_amount: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: false,
    comment: '贷款金额'
  },
  loan_term: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '贷款期限（月）'
  },
  interest_rate: {
    type: DataTypes.DECIMAL(5, 2),
    allowNull: false,
    comment: '贷款利率（%）'
  },
  contract_date: {
    type: DataTypes.DATEONLY,
    allowNull: false,
    comment: '合同签订日期'
  },
  status: {
    type: DataTypes.ENUM('active', 'completed', 'defaulted', 'cancelled'),
    allowNull: true,
    defaultValue: 'active',
    comment: '合同状态'
  }
}, {
  sequelize: require('../config/database').sequelize,
  modelName: 'LoanContract',
  tableName: 'loan_contracts',
  timestamps: true,
  underscored: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  // 移除不存在的字段
  omitNull: true
});

module.exports = LoanContract;