<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Enable PostGIS extension if not enabled
        DB::statement('CREATE EXTENSION IF NOT EXISTS postgis');
        
        Schema::create('locations', function (Blueprint $table) {
            $table->id();
            
            // Polymorphic relationship
            $table->morphs('locatable');
            
            // Location details
            $table->string('address')->nullable();
            $table->string('city');
            $table->string('state')->nullable();
            $table->string('country');
            $table->string('postal_code')->nullable();
            
            // Location name and type
            $table->string('name')->nullable();
            $table->string('location_type', 50)->nullable();
            
            // Legacy coordinate fields for backward compatibility
            $table->decimal('latitude', 9, 6)->nullable();
            $table->decimal('longitude', 9, 6)->nullable();
            
            // Coordinates using PostGIS
            // We'll add the coordinates column after the table is created
            $table->decimal('elevation', 8, 2)->nullable();
            
            // Additional details
            $table->string('timezone')->nullable();
            $table->json('metadata')->nullable();
            $table->boolean('is_approximate')->default(false);
            $table->string('source')->nullable();
            
            // Geocoding cache
            $table->json('geocoding_data')->nullable();
            $table->timestamp('geocoded_at')->nullable();
            
            // Timestamps
            $table->timestamps();
            
            // Indexes
            $table->index(['country', 'state', 'city']);
            $table->index('postal_code');
            $table->index('name');
            $table->index('location_type');
        });
        
        // Add the coordinates column using PostGIS
        DB::statement('ALTER TABLE locations ADD COLUMN coordinates GEOMETRY(Point, 4326)');
        DB::statement('CREATE INDEX locations_coordinates_idx ON locations USING GIST (coordinates)');
    }

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