require 'rails_helper'

RSpec.describe Youtube::VideoItem do
  describe '#initialize' do
    it 'extracts fields from YouTube video API item' do
      item = {
        'id' => 'video-1',
        'snippet' => {
          'title' => 'テスト動画',
          'channelId' => 'UC123',
          'publishedAt' => '2026-05-01T12:34:56Z',
          'tags' => ['tag-a', 'tag-b'],
          'thumbnails' => {
            'high' => {
              'url' => 'https://img.youtube.com/high.jpg'
            },
            'medium' => {
              'url' => 'https://img.youtube.com/medium.jpg'
            }
          }
        }
      }

      video = described_class.new(item)

      expect(video.id).to eq('video-1')
      expect(video.title).to eq('テスト動画')
      expect(video.channel_id).to eq('UC123')
      expect(video.published_at).to eq(Time.iso8601('2026-05-01T12:34:56Z'))
      expect(video.thumbnail_url).to eq('https://img.youtube.com/high.jpg')
      expect(video.raw_tags).to eq(['tag-a', 'tag-b'])
      expect(video.url).to eq('https://www.youtube.com/watch?v=video-1')
    end

    it 'uses highest priority thumbnail' do
      item = {
        'id' => 'video-1',
        'snippet' => {
          'title' => 'テスト動画',
          'channelId' => 'UC123',
          'publishedAt' => '2026-05-01T12:34:56Z',
          'thumbnails' => {
            'default' => {
              'url' => 'https://img.youtube.com/default.jpg'
            },
            'standard' => {
              'url' => 'https://img.youtube.com/standard.jpg'
            },
            'maxres' => {
              'url' => 'https://img.youtube.com/maxres.jpg'
            }
          }
        }
      }

      video = described_class.new(item)

      expect(video.thumbnail_url).to eq('https://img.youtube.com/maxres.jpg')
    end

    it 'falls back to empty raw tags' do
      item = {
        'id' => 'video-1',
        'snippet' => {
          'title' => 'テスト動画',
          'channelId' => 'UC123',
          'publishedAt' => '2026-05-01T12:34:56Z',
          'thumbnails' => {}
        }
      }

      video = described_class.new(item)

      expect(video.raw_tags).to eq([])
    end

    it 'returns nil thumbnail when no thumbnail exists' do
      item = {
        'id' => 'video-1',
        'snippet' => {
          'title' => 'テスト動画',
          'channelId' => 'UC123',
          'publishedAt' => '2026-05-01T12:34:56Z',
          'thumbnails' => {}
        }
      }

      video = described_class.new(item)

      expect(video.thumbnail_url).to be_nil
    end
  end
end
