const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const InsuranceApplication = sequelize.define('InsuranceApplication', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  application_no: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    validate: {
      len: [10, 50]
    }
  },
  customer_name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    validate: {
      len: [2, 100]
    }
  },
  customer_id_card: {
    type: DataTypes.STRING(18),
    allowNull: false,
    validate: {
      is: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/
    }
  },
  customer_phone: {
    type: DataTypes.STRING(20),
    allowNull: false,
    validate: {
      is: /^1[3-9]\d{9}$/
    }
  },
  customer_address: {
    type: DataTypes.STRING(255),
    allowNull: false,
    validate: {
      len: [5, 255]
    }
  },
  insurance_type_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'insurance_types',
      key: 'id'
    }
  },
  insurance_category: {
    type: DataTypes.STRING(50),
    allowNull: true,
    comment: '参保类型（如：牛、羊、猪等）',
    validate: {
      len: [1, 50]
    }
  },
  application_quantity: {
    type: DataTypes.INTEGER,
    allowNull: true,
    defaultValue: 1,
    comment: '申请数量',
    validate: {
      min: 1
    }
  },
  application_amount: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: false,
    validate: {
      min: 0
    }
  },
  status: {
    type: DataTypes.ENUM(
      'pending',           // 待初审
      'initial_approved',  // 初审通过待复核
      'under_review',      // 已支付待复核
      'approved',          // 已支付
      'rejected',          // 已拒绝
      'paid'              // 已支付
    ),
    defaultValue: 'pending',
    comment: '申请状态'
  },
  application_date: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  },
  review_notes: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  remarks: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '备注信息'
  },
  reviewer_id: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  review_date: {
    type: DataTypes.DATE,
    allowNull: true
  },
  documents: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: []
  }
}, {
  tableName: 'insurance_applications',
  timestamps: true,
  underscored: true,
  indexes: [
    { fields: ['application_no'] },
    { fields: ['customer_id_card'] },
    { fields: ['customer_phone'] },
    { fields: ['status'] },
    { fields: ['application_date'] },
    { fields: ['insurance_type_id'] },
    { fields: ['insurance_category'] },
    { fields: ['application_quantity'] },
    { fields: ['reviewer_id'] }
  ]
});

module.exports = InsuranceApplication;