# typed: strict
require_relative "../../app/lib/json_attr_helpers"
class MigrateFaPostColumnsToJsonAttrs < ActiveRecord::Migration[7.2]
  extend T::Sig
  include JsonAttrHelpers

  sig { void }
  def change
    # scanned at is a timestamp, but we store it as an int in state_detail,
    # so it requires special handling
    reversible { |dir| dir.up { execute <<~SQL } }
          UPDATE domain_fa_posts
          SET json_attributes = jsonb_set(
            json_attributes,
            '{scanned_at}',
            to_jsonb(to_char(to_timestamp((state_detail->'scanned_at')::int), 'YYYY-MM-DD HH24:MI:SS TZH:TZM')::text)
          )
          WHERE state_detail->'scanned_at' IS NOT NULL
        SQL

    migrate_json_table("domain_fa_posts") do
      migrate_column("title", :string, :text)
      migrate_column("category", :string, :text)
      migrate_column("theme", :string, :text)
      migrate_column("species", :string, :text)
      migrate_column("gender", :string, :text)
      migrate_column("description", :string, :text)
      migrate_column("keywords", :jsonb, :jsonb)
      migrate_column("num_favorites", :integer, :integer)
      migrate_column("num_comments", :integer, :integer)
      migrate_column("num_views", :integer, :integer)
      migrate_column("posted_at", :datetime, :timestamp)
      migrate_json_column("log_entry_detail", "last_submission_page_id")
      migrate_json_column("log_entry_detail", "first_browse_page_id")
      migrate_json_column("log_entry_detail", "first_gallery_page_id")
      migrate_json_column(
        "log_entry_detail",
        "first_seen_entry",
        "first_seen_entry_id",
      )
    end
  end
end
