require "rails_helper"

RSpec.describe MedicalReleasesController, type: :controller do
  render_views

  let(:user) { create(:user) }
  let(:account) { user.primary_account } 
  let(:project) { create(:project, account: user.primary_account) }

  before do
    sign_in user
  end

  describe "#index" do
    it "responds successfully" do
      get :index, params: { project_id: project }

      expect(response).to be_successful
    end

    it "renders content" do
      release = create(:medical_release, project: project,
                                        person_first_name: "My",
                                        person_last_name: "Release", 
                                        person_phone: "5551234567", 
                                        person_email: "jane.doe@test.com")
      create(:note, notable: release, content: "Some notes here")

      get :index, params: { project_id: project }

      expect(response.body).to have_content "My Release"
      expect(response.body).to have_content "Some notes here"
      expect(response.body).to have_content "Manage"
    end

    context "when there are no medical releases" do
      it "renders an empty message" do
        get :index, params: { project_id: project }

        expect(response.body).to have_content("Medical releases will appear here")
      end
    end

    context "when there are many records" do
      it "paginates the table" do
        create_list(:medical_release, 20, project: project)

        get :index, params: { project_id: project }

        expect(response.body).to have_link("2", href: project_medical_releases_path(project, page: 2))
      end
    end

    context "for xhr request" do
      it "filters the releases by a query param" do
        medical_releases = [
          create(:medical_release, person_name: "Adam Sandler", project: project),
          create(:medical_release, person_name: "Zoe Perry", project: project),
        ]

        get :index, params: { project_id: project, query: "Zoe" }, xhr: true

        expect(response.body).not_to have_content("Adam Sandler")
        expect(response.body).to have_content("Zoe Perry")
      end
    end
  end

  describe "#destroy" do
    let!(:medical_release) { create(:medical_release, project: project) }

    it "responds with redirect" do
      delete :destroy, params: { project_id: project, id: medical_release }

      expect(response).to be_redirect
      expect(response).to redirect_to [project, :medical_releases]
    end

    it "sets the flash" do
      delete :destroy, params: { project_id: project, id: medical_release }

      expect(flash.alert).not_to be_nil
    end

    it "destroys the record" do
      expect {
        delete :destroy, params: { project_id: project, id: medical_release }
      }.to change(MedicalRelease, :count).by(-1)
    end
  end
end
