class EnhanceMaterialManagement < ActiveRecord::Migration[8.0]
  def up
    change_table :materials, bulk: true do |t|
      t.integer :version_no, null: false, default: 1
    end

    change_table :material_versions, bulk: true do |t|
      t.string :event_type
      t.string :tag_name
      t.string :tag_category
      t.json :export_paths_json
      t.bigint :file_blob_id
      t.string :file_filename
      t.string :file_content_type
      t.bigint :file_byte_size
      t.string :file_checksum
      t.string :file_sha256
    end

    execute <<~SQL.squish
      UPDATE material_versions
      SET event_type = CASE
                       WHEN version_no = 1 THEN 'create'
                       ELSE 'update'
                       END
      WHERE event_type IS NULL
    SQL

    change_column_null :material_versions, :event_type, false
    add_index :material_versions, :file_blob_id

    add_check_constraint :material_versions,
                         "event_type IN ('create', 'update', 'discard', 'restore')",
                         name: 'material_versions_event_type_valid'

    create_table :material_export_items do |t|
      t.references :material, null: false, foreign_key: true
      t.string :profile, null: false, default: 'legacy_drive'
      t.string :export_path, null: false
      t.boolean :enabled, null: false, default: true
      t.references :created_by_user, foreign_key: { to_table: :users }
      t.timestamps

      t.index [:profile, :export_path], unique: true
      t.index [:material_id, :profile], unique: true
    end

    create_table :material_import_blocks do |t|
      t.string :match_kind, null: false
      t.string :sha256
      t.string :external_path_pattern
      t.string :reason, null: false
      t.text :note
      t.references :created_by_user, foreign_key: { to_table: :users }
      t.timestamps
    end

    execute <<~SQL.squish
      UPDATE materials
      SET version_no = COALESCE(
        (SELECT MAX(material_versions.version_no)
         FROM material_versions
         WHERE material_versions.material_id = materials.id),
        1)
    SQL
  end

  def down
    drop_table :material_import_blocks
    drop_table :material_export_items

    remove_check_constraint :material_versions, name: 'material_versions_event_type_valid'

    remove_index :material_versions, :file_blob_id
    remove_column :material_versions, :event_type
    remove_column :material_versions, :tag_name
    remove_column :material_versions, :tag_category
    remove_column :material_versions, :export_paths_json
    remove_column :material_versions, :file_blob_id
    remove_column :material_versions, :file_filename
    remove_column :material_versions, :file_content_type
    remove_column :material_versions, :file_byte_size
    remove_column :material_versions, :file_checksum
    remove_column :material_versions, :file_sha256

    remove_column :materials, :version_no
  end
end
