/**
 * 创建栏舍表迁移
 * @file 20250118000003_create_pens_table.js
 * @description 创建栏舍管理表
 */

'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('pens', {
      id: {
        type: Sequelize.BIGINT,
        primaryKey: true,
        autoIncrement: true,
        comment: '栏舍ID'
      },
      name: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: '栏舍名称'
      },
      animal_type: {
        type: Sequelize.ENUM('马', '牛', '羊', '家禽', '猪'),
        allowNull: false,
        comment: '动物类型'
      },
      pen_type: {
        type: Sequelize.STRING(50),
        allowNull: true,
        comment: '栏舍类型'
      },
      responsible: {
        type: Sequelize.STRING(20),
        allowNull: false,
        comment: '负责人'
      },
      capacity: {
        type: Sequelize.INTEGER,
        allowNull: false,
        defaultValue: 1,
        comment: '容量'
      },
      status: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: true,
        comment: '状态：true-开启，false-关闭'
      },
      description: {
        type: Sequelize.TEXT,
        allowNull: true,
        comment: '备注信息'
      },
      farm_id: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'farms',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        comment: '所属农场ID'
      },
      creator: {
        type: Sequelize.STRING(50),
        allowNull: false,
        defaultValue: 'admin',
        comment: '创建人'
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.NOW,
        comment: '创建时间'
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.NOW,
        comment: '更新时间'
      }
    }, {
      comment: '栏舍管理表',
      charset: 'utf8mb4',
      collate: 'utf8mb4_unicode_ci'
    });

    // 添加索引
    await queryInterface.addIndex('pens', ['name'], {
      name: 'idx_pens_name'
    });

    await queryInterface.addIndex('pens', ['animal_type'], {
      name: 'idx_pens_animal_type'
    });

    await queryInterface.addIndex('pens', ['farm_id'], {
      name: 'idx_pens_farm_id'
    });

    await queryInterface.addIndex('pens', ['status'], {
      name: 'idx_pens_status'
    });

    await queryInterface.addIndex('pens', ['created_at'], {
      name: 'idx_pens_created_at'
    });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('pens');
  }
};
