defmodule Mv.Repo.Migrations.AddSearchVectorToMembers do
  @moduledoc """
  Updates resources based on their most recent snapshots.

  This file was autogenerated with `mix ash_postgres.generate_migrations`
  """

  use Ecto.Migration

  def up do
    alter table(:members) do
      add :search_vector, :tsvector
    end

    execute("""
    CREATE INDEX members_search_vector_idx
    ON members
    USING GIN (search_vector)
    """)

    # Eigene Trigger-Funktion mit Gewichtung
    execute("""
    CREATE FUNCTION members_search_vector_trigger() RETURNS trigger AS $$
    BEGIN
      NEW.search_vector :=
        setweight(to_tsvector('simple', coalesce(NEW.first_name, '')), 'A') ||
        setweight(to_tsvector('simple', coalesce(NEW.last_name, '')), 'A') ||
        setweight(to_tsvector('simple', coalesce(NEW.email, '')), 'B') ||
        setweight(to_tsvector('simple', coalesce(NEW.birth_date::text, '')), 'C') ||
        setweight(to_tsvector('simple', coalesce(NEW.phone_number, '')), 'C') ||
        setweight(to_tsvector('simple', coalesce(NEW.join_date::text, '')), 'D') ||
        setweight(to_tsvector('simple', coalesce(NEW.exit_date::text, '')), 'D') ||
        setweight(to_tsvector('simple', coalesce(NEW.notes, '')), 'B') ||
        setweight(to_tsvector('simple', coalesce(NEW.city, '')), 'C') ||
        setweight(to_tsvector('simple', coalesce(NEW.street, '')), 'C') ||
        setweight(to_tsvector('simple', coalesce(NEW.house_number::text, '')), 'C') ||
        setweight(to_tsvector('simple', coalesce(NEW.postal_code::text, '')), 'C');
      RETURN NEW;
    END
    $$ LANGUAGE plpgsql;
    """)

    execute("""
    CREATE TRIGGER update_search_vector
    BEFORE INSERT OR UPDATE ON members
    FOR EACH ROW
    EXECUTE FUNCTION members_search_vector_trigger()
    """)
  end

  def down do
    execute("DROP TRIGGER IF EXISTS update_search_vector ON members")
    execute("DROP FUNCTION IF EXISTS members_search_vector_trigger()")
    execute("DROP INDEX IF EXISTS members_search_vector_idx")

    alter table(:members) do
      remove :search_vector
    end
  end
end
