<?php

use App\Repositories\Role;
use App\Repositories\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;

class AddSuperAdminEntryToRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('roles', function ($table) {
            $table->unique('name', 'roles_name_unique');
        });

        $user = User::where('email', 'kees@ggzecademy.nl')->with(['roles'])->first();

        // FIXME: move elsewhere, never run right now if things are set up properly
        if (!is_null($user)) {
            $super_admin_role = Role::create(['name' => 'super_admin', 'color' => 'black']);
            $admin_role = Role::where('name', 'admin')->first();
            $operator_role = Role::where('name', 'operator')->first();
            $user_role = Role::where('name', 'user')->first();

            $user->roles()->sync([
                $super_admin_role->id,
                $admin_role->id,
                $operator_role->id,
                $user_role->id
            ]);
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('roles', function ($table) {
            $table->dropUnique('roles_name_unique');
        });

        // Delete all role_user records with super admin role_id
        $admin_role = Role::where('name', 'super_admin')->first();
        DB::table('role_user')->where('role_id', $admin_role->id)->delete();

        // Delete super admin role
        $admin_role->delete();
    }
}
