<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class AlterTypeInMembersTable extends Migration
{
    const MEMBER_TYPE_ENUM_FIRST = 'A';
    const MEMBER_TYPE_ENUM_LAST = 'J';
    const MEMBER_TYPE_VALUE_DEFAULT = self::MEMBER_TYPE_ENUM_FIRST;
    const MEMBER_TYPE_VALUE_OLD = 'ggz';
    const MEMBER_TYPE_POSITION_AFTER = 'branch_id';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        /**
         * We currently drop and recreate the column instead of altering it due to a limitation in doctrine/dbal.
         *
         * @see https://github.com/laravel/framework/issues/1186
         */
        Schema::table('members', function (Blueprint $table) {
            $table->dropColumn('type');
        });

        Schema::table('members', function (Blueprint $table) {
            $enumChoices = range(self::MEMBER_TYPE_ENUM_FIRST, self::MEMBER_TYPE_ENUM_LAST);
            $table->enum('type', $enumChoices)
                ->default(self::MEMBER_TYPE_VALUE_DEFAULT)
                ->after(self::MEMBER_TYPE_POSITION_AFTER);
        });

        DB::table('members')
            ->whereNull('type')
            ->update(['type' => self::MEMBER_TYPE_VALUE_DEFAULT]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('members', function (Blueprint $table) {
            $table->string('type')->change();
        });

        DB::table('members')->update(['type' => self::MEMBER_TYPE_VALUE_OLD]);
    }
}
