# frozen_string_literal: true

class <%= @migration_class_name %> < ActiveRecord::Migration<%= ActiveRecord::VERSION::MAJOR < 5 ? '' : '[5.0]' %>
  def up
    execute <<-SQL
    CREATE 
      OR REPLACE FUNCTION metka_refresh_<%= view_name %>_materialized_view RETURNS TRIGGER LANGUAGE plpgsql AS $$
      BEGIN
        IF TG_OP = 'INSERT' AND NEW.<%= source_column_name %> IS NOT NULL THEN
          REFRESH MATERIALIZED VIEW CONCURRENTLY <%= view_name %>;
        ELSIF TG_OP = 'UPDATE' AND OLD.<%= source_column_name %> IS NOT NULL AND NEW.<%= source_column_name %> IS NOT NULL THEN
          REFRESH MATERIALIZED VIEW CONCURRENTLY <%= view_name %>;
        ELSIF TG_OP = 'DELETE' AND OLD.<%= source_column_name %> IS NOT NULL THEN
          REFRESH MATERIALIZED VIEW CONCURRENTLY <%= view_name %>;
        END IF;

      RETURN NULL;
    END $$;

    CREATE OR REPLACE MATERIALZIED VIEW <%= view_name %> AS

    SELECT UNNEST
      ( <%= source_column_name %> ) AS <%= source_column_name.singularize %>_name,
      COUNT ( * ) AS taggings_count
    FROM
      <%= source_table_name %>
    GROUP BY
      <%= source_column_name.singularize %>_name;

    CREATE TRIGGER metka_on_<%= source_table_name %>
    BEFORE UPDATE OR INSERT OR DELETE ON <%= source_table_name %> FOR EACH ROW
    EXECUTE PROCEDURE metka_refresh_<%= view_name %>_materialized_view();    
  end

  def down
    execute <<-SQL
      DROP VIEW <%= view_name %>;
    SQL
  end
end