<?php

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

/**
 * Item #3 — persist AI suggestions and extracted symptoms on the
 * appointment row so reloading the page doesn't re-spend LLM tokens
 * for unchanged Subjective text.
 *
 *  ai_subjective_hash      - sha1 of the Subjective text the cached
 *                            advice was generated for. If the current
 *                            #soap_s value hashes to the same string,
 *                            the page renders the cached values
 *                            without calling the AI.
 *  ai_exam_suggestions_json - {"suggested": [...], "reason": "..."}
 *  ai_symptoms_json        - {"findings": [...], "overall_concern": "..."}
 *  ai_advice_updated_at    - so we can show "Last analysed 5 min ago".
 */
class ClcAddAiCacheToAppointments extends Migration
{
    public function up()
    {
        if (!Schema::hasColumn('clc_appointments', 'ai_subjective_hash')) {
            Schema::table('clc_appointments', function (Blueprint $table) {
                $table->string('ai_subjective_hash', 40)->nullable()->index();
                $table->json('ai_exam_suggestions_json')->nullable();
                $table->json('ai_symptoms_json')->nullable();
                $table->timestamp('ai_advice_updated_at')->nullable();
            });
        }
    }

    public function down()
    {
        if (Schema::hasColumn('clc_appointments', 'ai_subjective_hash')) {
            Schema::table('clc_appointments', function (Blueprint $table) {
                $table->dropColumn([
                    'ai_subjective_hash',
                    'ai_exam_suggestions_json',
                    'ai_symptoms_json',
                    'ai_advice_updated_at',
                ]);
            });
        }
    }
}
