# frozen_string_literal: true

require 'rails_helper'

RSpec.describe Api::AcquiredMediaReleasesController, type: :controller do
  let(:current_user) { create(:user) }
  let(:project) { create(:project, name: 'first', account: current_user.primary_account) }

  describe '#index' do
    it 'returns a succesful response' do
      create(:acquired_media_release, name: 'ct1', project_id: project.id)

      sign_in_to_api(current_user)
      get :index, params: { project_id: project.id }

      expect(response).to be_successful
      old_body = response.body

      get :index, params: { project_id: project.id, updated_since: (DateTime.current + 10.days).to_date.to_s }
      expect(response.body).not_to eq(old_body)
    end
  end

  describe '#show' do
    it 'returns a succesful response' do
      tested_release = create(:acquired_media_release, name: 'ct1', project_id: project.id)

      sign_in_to_api(current_user)
      get :show, params: { id: tested_release.id }

      expect(response).to be_successful
    end
  end

  describe '#create' do
    before do
      template = create(:contract_template, name: 'ct1', project_id: project.id)
      signature = signature_base64
      @parameters = {
        contract_template_id: template.id,
        acquired_media_release: {
          signature: signature,
          person_phone: '123',
          name: 'aaa',
          signed_at: '2020-01-01 16:50:26 UTC'
        }
      }
      sign_in_to_api(current_user)
    end

    it 'returns 201 - created response' do
      post :create, params: @parameters
      expect(response.status).to eq 201

      expect(AcquiredMediaRelease.last.signature).to be_attached
    end

    it 'saves signed on date correctly' do
      post :create, params: @parameters
      expect(response.status).to eq 201
      expect(AcquiredMediaRelease.last.signed_on).to eq '01/01/20'
    end

    it 'runs attach contract to background job' do
      expect do
        post :create, params: @parameters
      end.to have_enqueued_job(AttachContractToReleasableJob).with(AcquiredMediaRelease.last)
    end

    it 'runs set tags for background releasable job' do
      expect do
        post :create, params: @parameters
      end.to have_enqueued_job(SetTagsForReleasableJob).with(AcquiredMediaRelease.last)
    end

    it 'fails if there is no signature' do
      template = create(:contract_template, name: 'ct1', project_id: project.id)
      parameters = {
        contract_template_id: template.id,
        acquired_media_release: {
          name: 'aaa'
        }
      }

      sign_in_to_api(current_user)
      expect do
        post :create, params: parameters
      end.to raise_error(ActiveRecord::RecordInvalid)
    end
  end

  private

  def signature_base64
    @signature_base64 ||= Base64Image.from_image(file_fixture('signature.png')).data_uri
  end

  def response_body_data_attributes
    JSON.parse(response.body).dig('data', 'attributes')
  end
end
