<?php

use App\Repositories\Member;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Webmozart\Assert\Assert;

class MigrateUserIdColumnFromMembersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        foreach (Member::all() as $member) {
            $member->users()->attach($member->user_id);
        }

        Schema::table('members', function (Blueprint $table) {
            $table->dropForeign('members_user_id_foreign');
            $table->dropColumn('user_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        if (!Schema::hasColumn('members', 'user_id')) {
            Schema::table('members', function (Blueprint $table) {
                $table->unsignedInteger('user_id')->nullable()->after('id');
                $table->foreign('user_id')->references('id')->on('users');
            });
        }

        $memberUserAll = DB::table('member_users')
            ->select(['member_id', 'user_id'])
            ->get();

        foreach ($memberUserAll as $memberUser) {
            Assert::notNull($memberUser->user_id);
        }

        foreach ($memberUserAll as $memberUser) {
            Member::findOrFail($memberUser->member_id)
                ->update(['user_id' => $memberUser->user_id]);
        }

        $amountMemberWithoutUser = DB::table('members')
            ->select('id')
            ->whereNull('user_id')
            ->count();
        Assert::eq(
            $amountMemberWithoutUser,
            0,
            sprintf(
                'Found %d member(s) without an attached user, expected 0.',
                $amountMemberWithoutUser,
            ),
        );

        Schema::table('members', function (Blueprint $table) {
            $table->unsignedInteger('user_id')->nullable(false)->change();
        });
    }
}
