<?php

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

/**
 * Audit log of every AI assistant interaction — prompt, response, token usage.
 * Kept for traceability (clinical advice must be auditable) and budget tracking.
 */
class CreateVaiQueriesTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('vai_queries')) return;

        Schema::create('vai_queries', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->unsignedInteger('user_id')->nullable();
            $table->unsignedInteger('appointment_id')->nullable();
            $table->unsignedInteger('pet_id')->nullable();
            $table->string('query_type', 30)->default('general');
            $table->text('prompt');
            $table->longText('response')->nullable();
            $table->string('model', 100)->nullable();
            $table->unsignedInteger('tokens_input')->nullable();
            $table->unsignedInteger('tokens_output')->nullable();
            $table->string('status', 20)->default('success'); // success | error
            $table->text('error')->nullable();
            $table->timestamps();

            $table->index(['business_id', 'created_at']);
            $table->index('appointment_id');
        });
    }

    public function down()
    {
        Schema::dropIfExists('vai_queries');
    }
}
