import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  // Check if workflow_templates table exists, if not create it
  const [tables] = await queryInterface.sequelize.query(`
    SELECT table_name 
    FROM information_schema.tables 
    WHERE table_schema = 'public' 
    AND table_name = 'workflow_templates';
  `);

  if (tables.length === 0) {
    // Create workflow_templates table if it doesn't exist
    await queryInterface.createTable('workflow_templates', {
      template_id: {
        type: DataTypes.UUID,
        primaryKey: true,
        defaultValue: DataTypes.UUIDV4
      },
      template_name: {
        type: DataTypes.STRING(200),
        allowNull: false
      },
      template_code: {
        type: DataTypes.STRING(50),
        allowNull: true,
        unique: true
      },
      template_description: {
        type: DataTypes.TEXT,
        allowNull: true
      },
      template_category: {
        type: DataTypes.STRING(100),
        allowNull: true
      },
      workflow_type: {
        type: DataTypes.STRING(50),
        allowNull: true
      },
      approval_levels_config: {
        type: DataTypes.JSONB,
        allowNull: true
      },
      default_tat_hours: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: true,
        defaultValue: 24
      },
      form_steps_config: {
        type: DataTypes.JSONB,
        allowNull: true
      },
      user_field_mappings: {
        type: DataTypes.JSONB,
        allowNull: true
      },
      dynamic_approver_config: {
        type: DataTypes.JSONB,
        allowNull: true
      },
      is_active: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: true
      },
      is_system_template: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false
      },
      usage_count: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0
      },
      created_by: {
        type: DataTypes.UUID,
        allowNull: true,
        references: {
          model: 'users',
          key: 'user_id'
        }
      },
      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('workflow_templates', ['template_code'], {
      name: 'idx_workflow_templates_template_code',
      unique: true
    });
    await queryInterface.addIndex('workflow_templates', ['workflow_type'], {
      name: 'idx_workflow_templates_workflow_type'
    });
    await queryInterface.addIndex('workflow_templates', ['is_active'], {
      name: 'idx_workflow_templates_is_active'
    });
  } else {
    // Table exists, add new columns if they don't exist
    const tableDescription = await queryInterface.describeTable('workflow_templates');

    if (!tableDescription.form_steps_config) {
      await queryInterface.addColumn('workflow_templates', 'form_steps_config', {
        type: DataTypes.JSONB,
        allowNull: true
      });
    }

    if (!tableDescription.user_field_mappings) {
      await queryInterface.addColumn('workflow_templates', 'user_field_mappings', {
        type: DataTypes.JSONB,
        allowNull: true
      });
    }

    if (!tableDescription.dynamic_approver_config) {
      await queryInterface.addColumn('workflow_templates', 'dynamic_approver_config', {
        type: DataTypes.JSONB,
        allowNull: true
      });
    }

    if (!tableDescription.workflow_type) {
      await queryInterface.addColumn('workflow_templates', 'workflow_type', {
        type: DataTypes.STRING(50),
        allowNull: true
      });
    }

    if (!tableDescription.is_system_template) {
      await queryInterface.addColumn('workflow_templates', 'is_system_template', {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false
      });
    }
  }
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  // Remove columns if they exist
  const tableDescription = await queryInterface.describeTable('workflow_templates');

  if (tableDescription.dynamic_approver_config) {
    await queryInterface.removeColumn('workflow_templates', 'dynamic_approver_config');
  }

  if (tableDescription.user_field_mappings) {
    await queryInterface.removeColumn('workflow_templates', 'user_field_mappings');
  }

  if (tableDescription.form_steps_config) {
    await queryInterface.removeColumn('workflow_templates', 'form_steps_config');
  }

  if (tableDescription.workflow_type) {
    await queryInterface.removeColumn('workflow_templates', 'workflow_type');
  }

  if (tableDescription.is_system_template) {
    await queryInterface.removeColumn('workflow_templates', 'is_system_template');
  }
}

