{{{
  exports({ to: app.migrationsPath(`${new Date().getTime()}_add_media_tenant_id.ts`) })
}}}
import { BaseSchema } from '@adonisjs/lucid/schema'

/**
 * Organizations as tenants for @adonis-agora/media: a nullable 'tenant_id' on 'media' (and on
 * 'media_upload_sessions' when the resumable session store uses Lucid). New files are stamped with
 * the active tenant once tenancy is on; existing rows stay NULL (see 'node ace media:tenancy:backfill').
 */
/**
 * The database schemas of 'media' and 'media_upload_sessions': the same values as 'schema' in
 * stores.lucid() and uploadSessions.lucid(). Leave them undefined for the connection's current one.
 */
const schema: string | undefined = undefined
const sessionsSchema: string | undefined = schema

export default class extends BaseSchema {
  async up() {
    if (this.db.dialect.name === 'mysql') {
      await this.upMysql()
    } else {
      this.in(schema).alterTable('media', (table) => {
        table.string('tenant_id').nullable()
        table.index(['tenant_id', 'owner_type', 'owner_id', 'collection'], 'media_tenant_owner_idx')
      })
    }
    if (await this.in(sessionsSchema).hasTable('media_upload_sessions')) {
      this.in(sessionsSchema).alterTable('media_upload_sessions', (table) => {
        table.string('tenant_id').nullable()
        table.index(['tenant_id'], 'media_upload_sessions_tenant_idx')
      })
    }
  }

  /**
   * MySQL caps an index key at 3072 bytes and four utf8mb4 VARCHAR(255) columns are 4080, so the
   * index covers the first 191 characters of each. Safe to re-run after a failed attempt: the column
   * is added only when missing.
   */
  private async upMysql() {
    // A dotted name, not withSchema(): knex's MySQL hasColumn ignores withSchema().
    const media = schema ? schema + '.media' : 'media'
    if (!(await this.schema.hasColumn(media, 'tenant_id'))) {
      this.in(schema).alterTable('media', (table) => {
        table.string('tenant_id').nullable()
      })
    }
    this.schema.raw(
      this.db
        .knexRawQuery('CREATE INDEX ?? ON ?? (??(191), ??(191), ??(191), ??(191))', [
          'media_tenant_owner_idx',
          media,
          'tenant_id',
          'owner_type',
          'owner_id',
          'collection',
        ])
        .toQuery()
    )
  }

  async down() {
    if (await this.in(sessionsSchema).hasTable('media_upload_sessions')) {
      this.in(sessionsSchema).alterTable('media_upload_sessions', (table) => {
        table.dropIndex(['tenant_id'], 'media_upload_sessions_tenant_idx')
        table.dropColumn('tenant_id')
      })
    }
    this.in(schema).alterTable('media', (table) => {
      table.dropIndex(['tenant_id', 'owner_type', 'owner_id', 'collection'], 'media_tenant_owner_idx')
      table.dropColumn('tenant_id')
    })
  }

  /** The schema builder, pointed at 'name' when it is set. */
  private in(name: string | undefined) {
    return name ? this.schema.withSchema(name) : this.schema
  }
}
