import { QueryInterface, DataTypes } from 'sequelize';

/**
 * Migration to create request_summaries table
 * Stores comprehensive summaries of closed workflow requests
 */
export async function up(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.createTable('request_summaries', {
    summary_id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      allowNull: false
    },
    request_id: {
      type: DataTypes.UUID,
      allowNull: false,
      references: {
        model: 'workflow_requests',
        key: 'request_id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'CASCADE',
      unique: true // One summary per request
    },
    initiator_id: {
      type: DataTypes.UUID,
      allowNull: false,
      references: {
        model: 'users',
        key: 'user_id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'CASCADE'
    },
    title: {
      type: DataTypes.STRING(500),
      allowNull: false
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    closing_remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    is_ai_generated: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    conclusion_id: {
      type: DataTypes.UUID,
      allowNull: true,
      references: {
        model: 'conclusion_remarks',
        key: 'conclusion_id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL'
    },
    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('request_summaries', ['request_id'], {
    name: 'idx_request_summaries_request_id'
  });

  await queryInterface.addIndex('request_summaries', ['initiator_id'], {
    name: 'idx_request_summaries_initiator_id'
  });

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

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

