<?php

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

return new class extends TenantMigration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('email_scheduled_recipients', function (Blueprint $table) {
            if (Schema::hasColumn('email_scheduled_recipients', 'user_id')) {
                $table->dropForeign(['user_id']);
                $table->renameColumn('user_id', 'member_id');
            }

            if (!Schema::hasColumn('email_scheduled_recipients', 'member_id')) {
                $table->unsignedBigInteger('member_id')->after('email_scheduled_id');
            }

            $table->foreign('member_id')
                ->references('id')->on('members')
                ->cascadeOnDelete();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('email_scheduled_recipients', function (Blueprint $table) {
            $table->dropForeign(['member_id']);
            $table->renameColumn('member_id', 'user_id');

            $table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();
        });
    }
};
