# typed: strict
class Domain::E621::Task::FixE621PostMissingFiles
  extend T::Sig
  include HasColorLogger

  sig { params(post: Domain::Post::E621Post).void }
  def run(post)
    index_page = post.last_index_page
    unless index_page
      logger.error("no index page for post #{post.id}")
      return
    end

    index_page_contents = index_page.response_bytes
    unless index_page_contents
      logger.error("no index page contents for post #{post.id}")
      return
    end

    index_page_json = JSON.parse(index_page_contents) if index_page_contents
    post_json = index_page_json["posts"].find { |p| p["id"] == post.e621_id }
    unless post_json
      logger.error("no post json for post #{post.id}")
      return
    end

    if post_json["file"]["md5"] != post.md5
      logger.error(
        "md5 mismatch for post #{post.id}: #{post.md5} != #{post_json["file"]["md5"]}",
      )
      return
    end

    post_updated =
      Domain::E621::TagUtil.initialize_or_update_post(
        post_json: post_json,
        caused_by_entry: post.last_index_page,
        force_update: true,
      )
    unless post_updated.id == post.id
      logger.error(
        "new post id mismatch for post #{post.id}: #{post_updated.id} != #{post.id}",
      )
      return
    end

    logger.info(
      "[fixed missing file][post id: #{post.id}][post e621_id: #{post.e621_id}]",
    )

    logger.error("post #{post.id} has no file") if !post_updated.file

    post_updated.save!
  end
end
