<?php

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

/**
 * One-time backfill of voice-transcription settings from the old VetAI
 * vai_settings table into existing ai_providers 'default' rows.
 *
 * AiProvider::forBusiness() imports these on FIRST creation, but businesses that
 * already had an ai_providers row before the VetAI→AiCore migration would miss
 * the carry-over. This fills the gap so no clinic loses its configured Whisper /
 * Web Speech voice setup. Only rows whose transcription block is still untouched
 * (t_provider IS NULL and use_separate_transcription = 0) are updated, so admin
 * edits made in AiCore Settings are never clobbered.
 */
class BackfillTranscriptionFromVaiSettings extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('ai_providers') || !Schema::hasTable('vai_settings')) {
            return;
        }

        foreach (DB::table('vai_settings')->get() as $vai) {
            $provider = DB::table('ai_providers')
                ->where('business_id', $vai->business_id)
                ->where('name', 'default')
                ->first();

            // Only touch existing, still-untouched provider rows. Missing rows
            // are handled lazily by AiProvider::forBusiness()'s own import.
            if (!$provider) {
                continue;
            }
            if (!empty($provider->t_provider) || !empty($provider->use_separate_transcription)) {
                continue;
            }

            $update = [
                'use_separate_transcription' => $vai->use_separate_transcription ?? 0,
                't_provider'                 => $vai->t_provider ?? null,
                't_base_url'                 => $vai->t_base_url ?? null,
                't_model'                    => $vai->t_model ?? null,
                't_language_hint'            => $vai->t_language_hint ?? 'auto',
                't_silence_limit_sec'        => $vai->t_silence_limit_sec ?? 30,
                't_clean_non_medical'        => $vai->t_clean_non_medical ?? 1,
                'auto_structure_soap'        => $vai->auto_structure_soap ?? 1,
                'consent_warning'            => $vai->consent_warning ?? 1,
            ];

            // t_api_key is stored with Laravel's 'encrypted' cast (no serialise).
            // Re-encrypt the same way so AiProvider's cast can read it back.
            if (!empty($vai->t_api_key)) {
                try {
                    $update['t_api_key'] = encrypt(decrypt($vai->t_api_key, false), false);
                } catch (\Throwable $e) {
                    // leave blank — admin can re-enter in AiCore Settings
                }
            }

            DB::table('ai_providers')->where('id', $provider->id)->update($update);
        }
    }

    public function down()
    {
        // Non-destructive backfill; nothing to reverse.
    }
}
