namespace :migration do
  desc '旧掲示板からデータを移行する．'
  task import: :environment do
    stats = { }
    sql = LegacyResponse.select('thread_id, MIN(date) AS first_date, MAX(date) AS last_date, COUNT(*) AS cnt')
                  .group('thread_id')
                  .to_sql
    LegacyResponse.connection.select_all(sql).each do |r|
      stats[r['thread_id'].to_i] = {
          first_date: r['first_date'],
          last_date:  r['last_date'],
          count:      r['cnt'].to_i }
    end

    ActiveRecord::Base.record_timestamps = false
    date = '1900-01-01 00:00:00'
    LegacyThread.find_each do |lt|
      date = stats[lt.id]&.[](:first_date) || date
      thread = Topic.find_or_create_by!(
          id:           lt.id + 1,
          name:         lt.title,
          description:  lt.explain.gsub('<p>', '').gsub('</p>', ''),
          created_at:   date,
          updated_at:   lt.latest)
    end
    ActiveRecord::Base.record_timestamps = true

    LegacyResponse.find_each do |lp|
      post = Post.new(
          thread_id:  lp.thread_id + 1,
          post_no:    lp.response_id,
          name:       lp.name == '名なしさん' ? nil : lp.name,
          message:    lp.message.presence,
          created_at: lp.date,
          updated_at: lp.date,
          held:       lp.held,
          deleted_at: lp.deleted ? lp.date : nil,
          good:       lp.good,
          bad:        lp.bad,
          sensitive:  false)

      post.password = lp.pass.presence

      if lp.image.present?
        path = ("/var/www/kekec/bbs/images/#{ lp.image }")
        if File.exist?(path)
          post.image.attach(io: File.open(path), filename: lp.image)
        end
      end

      post.save!
    end
  end
end
