import {DatabaseService, FieldType, Inject, Injectable, Migration} from '@extollo/lib'

/**
 * CreateSnippetsTableMigration
 * ----------------------------------
 * Create table to store code snippets and gists.
 */
@Injectable()
export default class CreateSnippetsTableMigration extends Migration {
    @Inject()
    protected readonly db!: DatabaseService

    /**
     * Apply the migration.
     */
    async up(): Promise<void> {
        const schema = this.db.get().schema()
        const table = await schema.table('snippets')

        table.primaryKey('snippet_id').required()

        table.column('slug')
            .type(FieldType.varchar)
            .required()

        table.column('users_only')
            .type(FieldType.bool)
            .default(false)

        table.column('single_access_only')
            .type(FieldType.bool)
            .default(false)

        table.column('access_key')
            .type(FieldType.varchar)
            .nullable()

        table.column('syntax')
            .type(FieldType.varchar)
            .nullable()

        table.column('body')
            .type(FieldType.text)
            .default('')

        await schema.commit(table)
    }

    /**
     * Undo the migration.
     */
    async down(): Promise<void> {
        const schema = this.db.get().schema()
        const table = await schema.table('snippets')

        table.dropIfExists()

        await schema.commit(table)
    }
}
