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

/**
 * CreatePageViewsTableMigration
 * ----------------------------------
 * Table to record analytics data
 */
@Injectable()
export default class CreatePageViewsTableMigration 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('page_views')

        table.primaryKey('page_view_id').required()

        table.column('visited_at')
            .type(FieldType.timestamp)
            .default(raw('NOW()'))
            .required()

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

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

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

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

        table.column('user_id')
            .type(FieldType.bigint)
            .nullable()

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

        await schema.commit(table)
    }

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

        table.dropIfExists()

        await schema.commit(table)
    }
}
