'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('document', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
      },
      company_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'company',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
        comment: 'Company this document belongs to'
      },
      document_number: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: 'Document number/code (e.g., RI/MF/D/01)'
      },
      title: {
        type: Sequelize.STRING(200),
        allowNull: false,
        comment: 'Document title/name'
      },
      category: {
        type: Sequelize.STRING(50),
        allowNull: true,
        comment: 'Document category (e.g., MF, QA, PUR, MKT, MN)'
      },
      document_type: {
        type: Sequelize.ENUM('D', 'F'),
        allowNull: true,
        comment: 'Document type: D (Directory/List) or F (Form)'
      },
      description: {
        type: Sequelize.TEXT,
        allowNull: true,
        comment: 'Additional description or notes'
      },
      status: {
        type: Sequelize.ENUM('ACTIVE', 'INACTIVE', 'DELETED'),
        allowNull: false,
        defaultValue: 'ACTIVE'
      },
      created_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        }
      },
      updated_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        }
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      }
    }, {
      tableName: 'document',
      comment: 'Document Master - List of documents (forms, lists, registers)'
    });

    // Create unique index on company_id and document_number
    await queryInterface.addIndex('document', ['company_id', 'document_number'], {
      unique: true,
      name: 'document_company_document_number_unique'
    });

    // Create index on company_id
    await queryInterface.addIndex('document', ['company_id'], {
      name: 'document_company_id_idx'
    });

    // Create index on status
    await queryInterface.addIndex('document', ['status'], {
      name: 'document_status_idx'
    });

    // Create index on category
    await queryInterface.addIndex('document', ['category'], {
      name: 'document_category_idx'
    });
  },

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

