require "rails_helper"

RSpec.describe Teachable::Api::V1::DataAccessController do

  context "#show" do
    let(:email) { "mike+#{SecureRandom.hex}@teachable.com" }
    let(:webinar) { create(:webinar, url: "test", time: Time.now + 2.days, basic_replay_bundle: nil, pro_replay_bundle: nil, basic_play_bundle: nil, pro_play_bundle: nil) }
    let(:registrant) { create(:registrant, email: email) }
    let!(:registration) { create(:registration, webinar: webinar, registrant: registrant) }
    it "returns json hash of User PII data" do

      get :show, params: {email: email, api_key: ENV["TEACHABLE_CROSS_PLATFORM_API_KEY"]}

      expect(JSON.parse(response.body)).to eq(
        {
          "registrant" => {
            "email" => email
          },
          "registrations" => [
            {
              "webinar_id" => webinar.id,
              "start_time" => registration.webinar_start_time.iso8601
            }
          ]
        }
      )
    end

    it "returns no_content if the email does not have any PII in the database" do
      get :show, params: {email: "foobar@example.com", api_key: ENV["TEACHABLE_CROSS_PLATFORM_API_KEY"]}
      expect(response.status).to eq 204
    end

    it "returns 'Missing email' message if email missing" do
      get :show, params: {api_key: ENV["TEACHABLE_CROSS_PLATFORM_API_KEY"]}
      expect(JSON.parse(response.body)).to eq({"error" => "Missing email param"})
    end
  end

end
