<?php

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

/**
 * Repoint `default_sender_phone_id` (on contact_templates) and `sender_phone_id`
 * (on contact_messages) away from the dialler's solicitor_phone_numbers table
 * onto the new solicitor_sms_senders whitelist.  Renames the columns in the
 * process to make the new ownership explicit.
 *
 * Safe to run when the contact hub is freshly migrated (no production rows
 * referencing solicitor_phone_numbers as SMS senders).  Drops the old columns
 * outright rather than dual-keeping them.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('contact_templates', function (Blueprint $t) {
            $t->dropForeign(['default_sender_phone_id']);
            $t->dropColumn('default_sender_phone_id');
        });
        Schema::table('contact_templates', function (Blueprint $t) {
            $t->foreignId('default_sms_sender_id')
                ->nullable()
                ->after('default_sender_email_id')
                ->constrained('solicitor_sms_senders')
                ->nullOnDelete();
        });

        Schema::table('contact_messages', function (Blueprint $t) {
            $t->dropForeign(['sender_phone_id']);
            $t->dropColumn('sender_phone_id');
        });
        Schema::table('contact_messages', function (Blueprint $t) {
            $t->foreignId('sms_sender_id')
                ->nullable()
                ->after('sender_email_id')
                ->constrained('solicitor_sms_senders')
                ->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('contact_messages', function (Blueprint $t) {
            $t->dropForeign(['sms_sender_id']);
            $t->dropColumn('sms_sender_id');
        });
        Schema::table('contact_messages', function (Blueprint $t) {
            $t->foreignId('sender_phone_id')
                ->nullable()
                ->after('sender_email_id')
                ->constrained('solicitor_phone_numbers')
                ->nullOnDelete();
        });

        Schema::table('contact_templates', function (Blueprint $t) {
            $t->dropForeign(['default_sms_sender_id']);
            $t->dropColumn('default_sms_sender_id');
        });
        Schema::table('contact_templates', function (Blueprint $t) {
            $t->foreignId('default_sender_phone_id')
                ->nullable()
                ->after('default_sender_email_id')
                ->constrained('solicitor_phone_numbers')
                ->nullOnDelete();
        });
    }
};
