text: const CreateThread = {
  
    databaseName: 'maha',
  
    up: async (knex) => {
  
      await knex.schema.alterTable('maha_profiles', function(table) {
        table.string('subscription_id')
        table.string('last_history_id')
        table.timestamp('deleted_at')
      })
  
      await knex.schema.createTable('maha_threads', (table) => {
        table.increments('id').primary()
        table.integer('team_id').unsigned().index().references('maha_teams.id')
        table.integer('profile_id').unsigned().index().references('maha_profiles.id')
        table.string('code')
        table.string('service_id')
        table.timestamps()
      })
  
      await knex.schema.alterTable('maha_emails', function(table) {
        table.integer('thread_id').unsigned().index().references('maha_threads.id')
        table.enum('priority', ['low','normal','high'], { useNative: true, enumName: 'maha_email_priorities' })
        table.string('service_id')
        table.string('message_id')
      })
  
      await knex.raw(`
        create view maha_email_details as
        select maha_emails.id as email_id,
        coalesce(maha_profiles.source::varchar, 'aws') as via,
        case
        when thread_id is not null then 'thread'
        when email_campaign_id is not null then 'campaign'
        when email_id is not null then 'automation'
        else 'system'
        end as type
        from maha_emails
        left join maha_threads on maha_threads.id=maha_emails.thread_id
        left join maha_profiles on maha_profiles.id=maha_threads.profile_id
      `)
  
      await knex.raw(`
        create view maha_thread_emails as
        select thread_id,
        id as email_id,
        row_number() over(partition by thread_id order by sent_at asc) - 1 as delta
        from maha_emails
        where thread_id is not null
      `)
  
      await knex.raw(`
        create view maha_thread_details as
        with totals as (
        select thread_id,
        count(*) as emails_count
        from maha_emails
        group by thread_id
        )
        select maha_emails.thread_id,
        maha_emails.program_id,
        maha_emails.contact_id,
        maha_emails.user_id,
        maha_emails.subject,
        maha_email_details.via,
        maha_emails.sent_at,
        totals.emails_count
        from maha_thread_emails
        inner join maha_emails on maha_emails.id=maha_thread_emails.email_id
        inner join maha_email_details on maha_email_details.email_id=maha_emails.id
        inner join totals on totals.thread_id=maha_thread_emails.thread_id
        where maha_thread_emails.delta=0
      `)
  
    },
  
    down: async (knex) => {
      await knex.schema.dropTable('maha_threads')
    }
  
  }
  
  export default CreateThread
  