<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('visits', function (Blueprint $table) {
            $table->id();
            $table->foreignId('mr_id')->constrained('mrs')->cascadeOnDelete();
            $table->date('visit_date');
            $table->foreignId('mapped_doctor_id')->nullable()->constrained('doctors')->nullOnDelete();
            $table->foreignId('area_id_resolved')->nullable()->constrained('areas')->nullOnDelete();
            $table->unsignedTinyInteger('confidence_score')->nullable()->comment('0-100 composite');
            $table->string('assignment_status', 30)->nullable()->comment('in_primary|in_secondary|outside|border_ambiguous');
            $table->json('flags')->nullable()->comment('geo_unknown, exception, etc.');
            $table->foreignId('import_batch_id')->nullable()->constrained('import_batches')->nullOnDelete();
            $table->foreignId('staging_row_id')->nullable()->constrained('visits_raw_staging')->nullOnDelete();
            $table->timestamps();

            $table->index(['mr_id', 'visit_date']);
            $table->index('assignment_status');
        });

        DB::statement('ALTER TABLE visits ADD COLUMN geom_point POINT NULL');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('visits');
    }
};
