require 'rails_helper'

RSpec.describe PostCreatePlan do
  def create_tag! name, category
    Tag.create!(name:, category:)
  end

  before do
    create_tag!('タグ希望', :meta)
    create_tag!('ニジラー情報不詳', :meta)
  end

  it 'plans direct and existing default tags without persisting records' do
    counts = [TagName.count, Tag.count]

    plan = described_class.new(
        attributes: {
            url: 'https://example.com/post',
            title: 'title',
            tags: 'character:new_character',
            parent_post_ids: '' }).build!

    expect(plan[:tags]).to eq('new_character')
    expect(plan[:direct_tag_specs]).to eq(
        [{ name: 'new_character', category: :character }])
    expect(plan[:default_tag_specs]).to include(
        { name: 'タグ希望', category: :meta },
        { name: 'ニジラー情報不詳', category: :meta })
    expect([TagName.count, Tag.count]).to eq(counts)
  end

  it 'resolves aliases and keeps tag sections separate from canonical names' do
    canonical = create_tag!('虹夏', :character)
    TagName.create!(name: 'にじか', canonical: canonical.tag_name)
    create_tag!('動画', :meta)

    plan = described_class.new(
        attributes: {
            url: 'https://example.com/video',
            title: 'video',
            tags: '動画 にじか[0:10-0:20]',
            duration: '1:00',
            parent_post_ids: '' }).build!

    expect(plan[:tags].split).to include('動画', '虹夏[0:10-0:20]')
    expect(plan[:display_tags]).to include(
        { name: '虹夏',
          category: 'character',
          section_literals: ['[0:10-0:20]'] })
    expect(plan[:video_ms]).to eq(60_000)
  end

  it 'validates a new tag name without persisting it' do
    long_name = 'a' * 256
    counts = [TagName.count, Tag.count]

    expect {
      described_class.new(
          attributes: {
              url: 'https://example.com/post',
              title: 'title',
              tags: long_name,
              parent_post_ids: '' }).build!
    }.to raise_error(ActiveRecord::RecordInvalid) { |error|
      expect(error.record.errors[:tags]).not_to be_empty
    }
    expect([TagName.count, Tag.count]).to eq(counts)
  end

  it 'ignores duration when the planned tags do not include video' do
    plan = described_class.new(
        attributes: {
            url: 'https://example.com/post',
            title: 'title',
            tags: 'ordinary_tag',
            duration: 'invalid',
            parent_post_ids: '' }).build!

    expect(plan[:duration]).to eq('invalid')
    expect(plan[:video_ms]).to be_nil
  end
end
