class CreateReleaseAssetsAndBackfill < ActiveRecord::Migration[8.1]
  COLUMN_KINDS = {
    "cartridge_path"   => "cartridge",
    "source_path"      => "source",
    "html_folder_path" => "html",
    "docs_folder_path" => "docs"
  }.freeze

  def up
    create_table :release_assets, id: { type: :bigint, unsigned: true } do |t|
      t.bigint   :release_id, unsigned: true, null: false
      t.string   :kind,       limit: 32,      null: false
      t.string   :path,                       null: false
      t.datetime :deleted_at, precision: 3
      t.timestamps precision: 3
    end

    add_index :release_assets, [ :release_id, :kind ], unique: true, name: "idx_release_assets_release_kind"
    add_index :release_assets, :deleted_at, name: "idx_release_assets_deleted_at"
    add_index :release_assets, :path, name: "idx_release_assets_path"
    add_foreign_key :release_assets, :releases, name: "fk_releases_release_assets", on_delete: :cascade

    # A soft-deletelt release-ek asset sorai a release deleted_at-jét öröklik,
    # így az unscoped alapú admin/updater logika konzisztens marad.
    COLUMN_KINDS.each do |column, kind|
      execute <<~SQL.squish
        INSERT INTO release_assets (release_id, kind, path, deleted_at, created_at, updated_at)
        SELECT id, '#{kind}', #{column}, deleted_at, NOW(3), NOW(3)
        FROM releases
        WHERE #{column} IS NOT NULL AND #{column} != ''
      SQL
    end
  end

  def down
    COLUMN_KINDS.each do |column, kind|
      execute <<~SQL.squish
        UPDATE releases r
        JOIN release_assets ra ON ra.release_id = r.id AND ra.kind = '#{kind}'
        SET r.#{column} = ra.path
      SQL
    end

    drop_table :release_assets
  end
end
