defmodule Aprsme.Repo.Migrations.FixDecrementPacketSequenceTrigger do
  use Ecto.Migration

  def up do
    execute """
    CREATE OR REPLACE FUNCTION decrement_packet_sequence()
    RETURNS TRIGGER AS $$
    DECLARE
      current_val BIGINT;
    BEGIN
      BEGIN
        current_val := currval('packet_count_seq');
      EXCEPTION
        WHEN object_not_in_prerequisite_state THEN
          SELECT last_value INTO current_val FROM packet_count_seq;
      END;
      PERFORM setval('packet_count_seq', GREATEST(0, current_val - 1), true);
      RETURN OLD;
    END;
    $$ LANGUAGE plpgsql;
    """
  end

  def down do
    execute """
    CREATE OR REPLACE FUNCTION decrement_packet_sequence()
    RETURNS TRIGGER AS $$
    BEGIN
      PERFORM setval('packet_count_seq', GREATEST(0, currval('packet_count_seq') - 1), true);
      RETURN OLD;
    END;
    $$ LANGUAGE plpgsql;
    """
  end
end
