'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('fiscal_period', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      fiscal_year_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'fiscal_year',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      period_number: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: 'Period number (1-12 for monthly periods)'
      },
      period_code: {
        type: Sequelize.STRING(10),
        allowNull: false,
        comment: 'Period code (e.g., P01, P02)'
      },
      period_name: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: 'Period name (e.g., April 2024)'
      },
      start_date: {
        type: Sequelize.DATEONLY,
        allowNull: false
      },
      end_date: {
        type: Sequelize.DATEONLY,
        allowNull: false
      },
      is_closed: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: false
      },
      closed_date: {
        type: Sequelize.DATEONLY,
        allowNull: true
      },
      closed_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      },
      status: {
        type: Sequelize.ENUM('OPEN', 'CLOSED', 'LOCKED'),
        allowNull: false,
        defaultValue: 'OPEN'
      },
      created_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updated_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
      }
    });

    await queryInterface.addIndex('fiscal_period', ['fiscal_year_id', 'period_number'], { unique: true });
    await queryInterface.addIndex('fiscal_period', ['start_date', 'end_date']);
    await queryInterface.addIndex('fiscal_period', ['status']);
  },

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

