<?php

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

class AddUserToAccountoauth extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
    	Schema::table('users',function(Blueprint $table) {
			$table->index(['id','site_id'],'site_user_id_idx');
		});

		Schema::table('ab_account_oauth', function (Blueprint $table) {
			$table->dropPrimary(['id','site_id','account_id','oauth_id']);
			$table->primary(['id','site_id','oauth_id']);
		});

		Schema::table('ab_account_oauth', function (Blueprint $table) {
			$table->bigInteger('account_id')->nullable()->change();

			$table->integer('user_id')->unsigned()->nullable();
			$table->unique(['site_id','user_id','oauth_id']);
			$table->index(['user_id','site_id'],'site_user_id_idx');
			$table->foreign(['user_id','site_id'],'site_user_id')->references(['id','site_id'])->on('users');
		});

		Schema::table('ab_oauth', function (Blueprint $table) {
        	$table->string('name',32)->change();
            $table->unique(['site_id','name']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
		Schema::table('ab_account_oauth', function (Blueprint $table) {
			$table->dropPrimary(['id','site_id','oauth_id']);
			$table->primary(['id','site_id','account_id','oauth_id']);
		});

		Schema::table('ab_account_oauth', function (Blueprint $table) {
			$table->dropForeign('site_user_id');
			$table->dropUnique(['site_id','user_id','oauth_id']);
			$table->dropIndex('site_user_id_idx');
			$table->dropColumn('user_id');

			$table->bigInteger('account_id')->change();
		});

		Schema::table('users',function(Blueprint $table) {
			$table->dropIndex('site_user_id_idx');
		});

        Schema::table('ab_oauth', function (Blueprint $table) {
			$table->string('name',32)->nullable()->change();
			$table->dropUnique(['site_id','name']);
        });
    }
}
