import { QueryInterface, DataTypes } from 'sequelize';

/**
 * Migration to create conclusion_remarks table
 * Stores AI-generated and finalized conclusion remarks for workflow requests
 */
export async function up(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.createTable('conclusion_remarks', {
    conclusion_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 conclusion per request
    },
    ai_generated_remark: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    ai_model_used: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    ai_confidence_score: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: true
    },
    final_remark: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    edited_by: {
      type: DataTypes.UUID,
      allowNull: true,
      references: {
        model: 'users',
        key: 'user_id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL'
    },
    is_edited: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    edit_count: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0
    },
    approval_summary: {
      type: DataTypes.JSONB,
      allowNull: true
    },
    document_summary: {
      type: DataTypes.JSONB,
      allowNull: true
    },
    key_discussion_points: {
      type: DataTypes.ARRAY(DataTypes.TEXT),
      allowNull: false,
      defaultValue: []
    },
    generated_at: {
      type: DataTypes.DATE,
      allowNull: true
    },
    finalized_at: {
      type: DataTypes.DATE,
      allowNull: true
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    }
  });

  // Add index on request_id for faster lookups
  await queryInterface.addIndex('conclusion_remarks', ['request_id'], {
    name: 'idx_conclusion_remarks_request_id'
  });

  // Add index on finalized_at for KPI queries
  await queryInterface.addIndex('conclusion_remarks', ['finalized_at'], {
    name: 'idx_conclusion_remarks_finalized_at'
  });
}

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

