<?php

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

/**
 * Two-way sync between appointment lab/exam results (clc_appointments.exam_results JSON)
 * and Medical Reports (clc_medical_reports).
 *   - source   : 'manual' (created in the Medical Reports screen) or
 *                'appointment_lab' (auto-created from an appointment exam/lab result)
 *   - exam_key : the stable key of the matching entry inside exam_results JSON,
 *                used to locate and write back the synced result.
 */
class AddSyncColumnsToClcMedicalReports extends Migration
{
    public function up()
    {
        Schema::table('clc_medical_reports', function (Blueprint $table) {
            if (!Schema::hasColumn('clc_medical_reports', 'source')) {
                $table->string('source', 30)->default('manual')->after('report_type');
            }
            if (!Schema::hasColumn('clc_medical_reports', 'exam_key')) {
                $table->string('exam_key', 100)->nullable()->after('source');
            }
        });

        // Index to find the synced report for a given appointment exam entry fast
        if (Schema::hasColumn('clc_medical_reports', 'exam_key')) {
            try {
                Schema::table('clc_medical_reports', function (Blueprint $table) {
                    $table->index(['appointment_id', 'exam_key'], 'clc_medrep_apt_examkey_idx');
                });
            } catch (\Throwable $e) {
                // index already exists — ignore
            }
        }
    }

    public function down()
    {
        Schema::table('clc_medical_reports', function (Blueprint $table) {
            try { $table->dropIndex('clc_medrep_apt_examkey_idx'); } catch (\Throwable $e) {}
            if (Schema::hasColumn('clc_medical_reports', 'exam_key')) {
                $table->dropColumn('exam_key');
            }
            if (Schema::hasColumn('clc_medical_reports', 'source')) {
                $table->dropColumn('source');
            }
        });
    }
}
