import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  // Create internal_orders table for storing IO (Internal Order) details
  await queryInterface.createTable('internal_orders', {
    io_id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4
    },
    request_id: {
      type: DataTypes.UUID,
      allowNull: false,
      references: {
        model: 'workflow_requests',
        key: 'request_id'
      },
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE'
    },
    io_number: {
      type: DataTypes.STRING(50),
      allowNull: false
    },
    io_remark: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    io_available_balance: {
      type: DataTypes.DECIMAL(15, 2),
      allowNull: true
    },
    io_blocked_amount: {
      type: DataTypes.DECIMAL(15, 2),
      allowNull: true
    },
    io_remaining_balance: {
      type: DataTypes.DECIMAL(15, 2),
      allowNull: true
    },
    organized_by: {
      type: DataTypes.UUID,
      allowNull: true,
      references: {
        model: 'users',
        key: 'user_id'
      },
      onDelete: 'SET NULL',
      onUpdate: 'CASCADE'
    },
    organized_at: {
      type: DataTypes.DATE,
      allowNull: true
    },
    sap_document_number: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('PENDING', 'BLOCKED', 'RELEASED', 'CANCELLED'),
      defaultValue: 'PENDING',
      allowNull: false
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    }
  });

  // Create indexes
  await queryInterface.addIndex('internal_orders', ['io_number'], {
    name: 'idx_internal_orders_io_number'
  });

  await queryInterface.addIndex('internal_orders', ['organized_by'], {
    name: 'idx_internal_orders_organized_by'
  });

  // Create unique constraint: one IO per request (unique index on request_id)
  await queryInterface.addIndex('internal_orders', ['request_id'], {
    name: 'idx_internal_orders_request_id_unique',
    unique: true
  });
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.dropTable('internal_orders');
}

