<?php

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

/**
 * Wire the specialty registry into the shared engine: every appointment is
 * tagged with the specialty it belongs to, and a patient may carry an optional
 * default specialty. A patient is ONE global profile and can be seen by any
 * specialty without pre-enrollment.
 */
class AddSpecialtyColumns extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_appointments') && ! Schema::hasColumn('clc_appointments', 'specialty_id')) {
            Schema::table('clc_appointments', function (Blueprint $table) {
                $table->unsignedInteger('specialty_id')->nullable()->after('business_id');
                $table->index('specialty_id');
                $table->foreign('specialty_id')->references('id')->on('clc_specialties')->nullOnDelete();
            });
        }

        if (Schema::hasTable('clc_patients') && ! Schema::hasColumn('clc_patients', 'default_specialty_id')) {
            Schema::table('clc_patients', function (Blueprint $table) {
                $table->unsignedInteger('default_specialty_id')->nullable()->after('business_id');
                $table->foreign('default_specialty_id')->references('id')->on('clc_specialties')->nullOnDelete();
            });
        }
    }

    public function down()
    {
        if (Schema::hasColumn('clc_appointments', 'specialty_id')) {
            Schema::table('clc_appointments', function (Blueprint $table) {
                $table->dropForeign(['specialty_id']);
                $table->dropColumn('specialty_id');
            });
        }
        if (Schema::hasColumn('clc_patients', 'default_specialty_id')) {
            Schema::table('clc_patients', function (Blueprint $table) {
                $table->dropForeign(['default_specialty_id']);
                $table->dropColumn('default_specialty_id');
            });
        }
    }
}
