require 'rails_helper'

RSpec.describe 'TheatreProgrammes', type: :request do
  describe 'GET /theatres/:theatre_id/programmes' do
    let(:theatre) { create(:theatre) }
    let(:other_theatre) { create(:theatre) }
    let(:post_1) { Post.create!(title: 'first', url: 'https://www.nicovideo.jp/watch/sm1') }
    let(:post_2) { Post.create!(title: 'second', url: 'https://www.nicovideo.jp/watch/sm2') }
    let(:other_post) { Post.create!(title: 'other', url: 'https://www.nicovideo.jp/watch/sm3') }

    before do
      TheatreProgramme.create!(theatre:, position: 1, post: post_1, created_at: 2.minutes.ago)
      TheatreProgramme.create!(theatre:, position: 2, post: post_2, created_at: 1.minute.ago)
      TheatreProgramme.create!(
        theatre: other_theatre,
        position: 1,
        post: other_post,
        created_at: 1.minute.ago
      )
    end

    it 'returns programmes for the theatre in descending position with post json' do
      get "/theatres/#{theatre.id}/programmes"

      expect(response).to have_http_status(:ok)
      expect(json.map { _1['position'] }).to eq([2, 1])
      expect(json.map { _1.dig('post', 'title') }).to eq(['second', 'first'])
      expect(json.first['post']).to include('id' => post_2.id, 'url' => post_2.url)
    end

    it 'filters programmes by position_gt' do
      get "/theatres/#{theatre.id}/programmes", params: { position_gt: 1 }

      expect(response).to have_http_status(:ok)
      expect(json.map { _1['position'] }).to eq([2])
    end
  end
end
