import { QueryInterface, DataTypes } from 'sequelize';

/**
 * Migration to create shared_summaries table
 * Stores sharing relationships for request summaries
 */
export async function up(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.createTable('shared_summaries', {
    shared_summary_id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      allowNull: false
    },
    summary_id: {
      type: DataTypes.UUID,
      allowNull: false,
      references: {
        model: 'request_summaries',
        key: 'summary_id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'CASCADE'
    },
    shared_by: {
      type: DataTypes.UUID,
      allowNull: false,
      references: {
        model: 'users',
        key: 'user_id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'CASCADE'
    },
    shared_with: {
      type: DataTypes.UUID,
      allowNull: false,
      references: {
        model: 'users',
        key: 'user_id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'CASCADE'
    },
    shared_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    viewed_at: {
      type: DataTypes.DATE,
      allowNull: true
    },
    is_read: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    }
  });

  // Create unique constraint to prevent duplicate shares
  await queryInterface.addConstraint('shared_summaries', {
    fields: ['summary_id', 'shared_with'],
    type: 'unique',
    name: 'uk_shared_summary'
  });

  // Create indexes
  await queryInterface.addIndex('shared_summaries', ['summary_id'], {
    name: 'idx_shared_summaries_summary_id'
  });

  await queryInterface.addIndex('shared_summaries', ['shared_by'], {
    name: 'idx_shared_summaries_shared_by'
  });

  await queryInterface.addIndex('shared_summaries', ['shared_with'], {
    name: 'idx_shared_summaries_shared_with'
  });

  await queryInterface.addIndex('shared_summaries', ['shared_at'], {
    name: 'idx_shared_summaries_shared_at'
  });
}

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

