<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('location', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->uuid('uuid');
            $table->string('name', length: 255);
            $table->string('url', length: 255);
            $table->text('public_comments');
            $table->json('images')->nullable();
            $table->boolean('active');
            $table->string('rating', length: 255);
            $table->integer('added_by');
            $table->timestamps(precision: 0);
            $table->timestamp('deleted_at', precision: 0)->nullable();
            $table->string('tags', length: 255);
            $table->integer('block_count')->nullable();
            $table->integer('silence_count')->nullable();
            $table->integer('actions_count')->nullable();
            $table->text('archive_links')->nullable();
            $table->json('block_vote')->nullable();
            $table->json('silence_vote')->nullable();
            $table->text('notes')->nullable();
        });

        DB::statement("ALTER TABLE location ADD COLUMN searchtext TSVECTOR");
        DB::statement("UPDATE location SET searchtext = to_tsvector('english', name)");
        DB::statement("UPDATE location SET searchtext = to_tsvector('english', url)");
        DB::statement("UPDATE location SET searchtext = to_tsvector('english', public_comments)");
        DB::statement("UPDATE location SET searchtext = to_tsvector('english', tags)");
        DB::statement("CREATE INDEX searchtext_gin ON location USING GIN(searchtext)");
        DB::statement("CREATE TRIGGER ts_searchtext BEFORE INSERT OR UPDATE ON location FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger('searchtext', 'pg_catalog.english', 'name', 'url', 'public_comments', 'tags')");
    }

    //'name', 'url', 'public_comments', 'tags'

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        DB::statement("DROP TRIGGER IF EXISTS tsvector_update_trigger ON location");
        DB::statement("DROP INDEX IF EXISTS searchtext_gin");
        DB::statement("ALTER TABLE location DROP COLUMN searchtext");
        Schema::dropIfExists('location');
    }
};
