<?php

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

/**
 * Additive extension of ClinicCore's clc_departments (spec §5 department;
 * REUSE-MAP §5 "extend"). Lives inside MedOrganization so ClinicCore stays
 * untouched; every column is guarded with Schema::hasColumn so re-running or
 * a future ClinicCore version adding the same columns is harmless.
 *
 * business_location_id references core business_locations (the facility),
 * unlike the existing location_id which references clc_clinic_locations.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('clc_departments')) {
            return; // ClinicCore not migrated yet — module.json requires it first.
        }

        Schema::table('clc_departments', function (Blueprint $t) {
            if (! Schema::hasColumn('clc_departments', 'code')) {
                $t->string('code', 20)->nullable()->after('name');
            }
            if (! Schema::hasColumn('clc_departments', 'dept_type')) {
                $t->enum('dept_type', ['clinical', 'diagnostic', 'administrative', 'support'])
                    ->nullable()->after('code');
            }
            if (! Schema::hasColumn('clc_departments', 'parent_department_id')) {
                $t->unsignedInteger('parent_department_id')->nullable()->after('dept_type');
            }
            if (! Schema::hasColumn('clc_departments', 'head_user_id')) {
                $t->unsignedInteger('head_user_id')->nullable()->after('parent_department_id');
            }
            if (! Schema::hasColumn('clc_departments', 'working_hours')) {
                $t->json('working_hours')->nullable()->after('head_user_id');
            }
            if (! Schema::hasColumn('clc_departments', 'business_location_id')) {
                $t->unsignedInteger('business_location_id')->nullable()->after('working_hours');
            }
            if (! Schema::hasColumn('clc_departments', 'modules_enabled')) {
                $t->json('modules_enabled')->nullable()->after('business_location_id');
            }
            if (! Schema::hasColumn('clc_departments', 'sort_order')) {
                $t->integer('sort_order')->default(0)->after('modules_enabled');
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('clc_departments')) {
            return;
        }

        Schema::table('clc_departments', function (Blueprint $t) {
            foreach ([
                'code', 'dept_type', 'parent_department_id', 'head_user_id',
                'working_hours', 'business_location_id', 'modules_enabled', 'sort_order',
            ] as $column) {
                if (Schema::hasColumn('clc_departments', $column)) {
                    $t->dropColumn($column);
                }
            }
        });
    }
};
