<?php

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

return new class extends Migration
{
    // add composite + geo + optional fulltext indexes to locations
    public function up(): void
    {
        $driver = Schema::getConnection()->getDriverName();

        Schema::table('locations', function (Blueprint $table) use ($driver) {
            // composite btree index for common lookups
            $table->index(
                ['display_name', 'city', 'state', 'postal', 'country'],
                'locations_name_city_idx'
            );

            // simple btree index to speed bounding-box geo lookups
            $table->index(['lat', 'lon'], 'locations_lat_lon_idx');

            // optional: fulltext index for free-form text searching
            // note: requires mysql/mariadb version with innodb fulltext support
            if (in_array($driver, ['mysql', 'pgsql'], true)) {
                $table->fullText('raw_address', 'locations_raw_address_fulltext');
            }
        });
    }

    // drop the indexes added in up()
    public function down(): void
    {
        $driver = Schema::getConnection()->getDriverName();

        Schema::table('locations', function (Blueprint $table) use ($driver) {
            $table->dropIndex('locations_name_city_idx');
            $table->dropIndex('locations_lat_lon_idx');
            if (in_array($driver, ['mysql', 'pgsql'], true)) {
                $table->dropFullText('locations_raw_address_fulltext');
            }
        });
    }
};
