require 'rails_helper'

RSpec.describe 'database seeds' do
  before do
    PostUrlSanitisationRule.unscoped.delete_all
  end

  it 'registers the initial post URL sanitisation rules' do
    load_seeds

    urls = {
      'https://youtu.be/abc123?si=share' => youtube_url('abc123'),
      'https://www.youtube.com/live/abc123?t=10' => youtube_url('abc123'),
      'https://youtube.com/shorts/abc123?feature=share' => youtube_url('abc123'),
      'https://m.youtube.com/embed/abc123' => youtube_url('abc123'),
      'https://youtube.com/watch?feature=share&v=abc123&t=10' => youtube_url('abc123'),
      'https://nico.ms/sm123?from=share#fragment' => nico_url('sm123'),
      'https://www.nicovideo.jp/watch/sm123?ref=share#fragment' => nico_url('sm123')
    }

    expect(PostUrlSanitisationRule.count).to eq(7)
    urls.each do |url, canonical_url|
      expect(PostUrlSanitisationRule.sanitise(url)).to eq(canonical_url)
    end
  end

  it 'does not overwrite or restore an existing rule' do
    rule = PostUrlSanitisationRule.create!(
      priority: 10,
      source_pattern: '\Ahttps://example\.com/custom\z',
      replacement: 'https://example.com/replacement'
    )
    rule.discard!
    original_attributes = rule.reload.attributes

    2.times { load_seeds }

    persisted_rule = PostUrlSanitisationRule.unscoped.find(10)
    expect(persisted_rule.attributes).to eq(original_attributes)
    expect(PostUrlSanitisationRule.unscoped.count).to eq(7)
  end

  it 'does not duplicate a rule moved to another priority' do
    source_pattern = '\Ahttps?://youtu\.be/([^/?#]+)(?:[?#].*)?\z'
    PostUrlSanitisationRule.create!(
      priority: 80,
      source_pattern:,
      replacement: 'https://example.com/custom/\1'
    )

    load_seeds

    rules = PostUrlSanitisationRule.unscoped
    expect(rules.where(source_pattern:).count).to eq(1)
    expect(rules.find(80).replacement).to eq('https://example.com/custom/\1')
  end

  def load_seeds
    load Rails.root.join('db/seeds.rb')
  end

  def youtube_url(video_id) = "https://www.youtube.com/watch?v=#{ video_id }"

  def nico_url(video_id) = "https://www.nicovideo.jp/watch/#{ video_id }"
end
