package io.delphi.qa.auto.awsmfrw.tests.slz.api;

import io.delphi.qa.auto.awsmfrw.common_baby.IsaCommonMethods;
import io.delphi.qa.auto.awsmfrw.common_baby.delphi.aws.EnAwsSecrets;
import io.delphi.qa.auto.awsmfrw.common_baby.delphi.slz.EnSlzSpotifyApiEps;
import io.delphi.qa.auto.awsmfrw.common_baby.delphi.slz.EnSlzSpotifyApiResources;
import io.delphi.qa.auto.awsmfrw.models.api.rest.slz.spotify.RsSpotifyApiToken;
import io.delphi.qa.auto.awsmfrw.models.aws.sf.RqSlzJobManager;
import io.delphi.qa.auto.awsmfrw.tests.BsTestCase;
import io.qameta.allure.Epic;
import io.qameta.allure.Issue;
import io.restassured.mapper.ObjectMapperType;
import org.hamcrest.Matchers;
import org.hamcrest.core.AnyOf;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Epic("DAE-427\\[AUTO][SLZ] Automation Framework")
public class Test_SlzApiDspSpotifyApiHealthCheck extends BsTestCase {

  @Override
  public String genTestRunId() {
    return IsaCommonMethods.testRunId();
  }

  @Issue("DAE-803")
  @Test
  @Parameters({"reportNameText"})
  public void tc1_whenReportDateMinus2Days_thenStatusCodeAnyOfValid(
      @Optional("spotify-sme-streams-v4") String reportNameText) {
    Map<String, String> secretOAuth = fetchAwsSecret(EnAwsSecrets.DELPHI_SLZ_SPOTIFY_V2);
    RsSpotifyApiToken authToken =
        delphi
            .api()
            .rest()
            .spotifyApi(false)
            .withFormParams(
                new HashMap<String, Object>() {
                  {
                    put("grant_type", "client_credentials");
                    put("client_id", secretOAuth.get("client_id"));
                    put("client_secret", secretOAuth.get("client_secret"));
                  }
                })
            .execPost(EnSlzSpotifyApiEps.AUTH.get())
            .withThen()
            .withValidatableRs()
            .statusCode(200)
            .extract()
            .as(RsSpotifyApiToken.class, ObjectMapperType.GSON);
    List<RqSlzJobManager> jobs = delphi.fs().listSfRqSlzMainFlow(reportNameText);
    int index = jobs.size() > 1 ? IsaCommonMethods.random.nextInt(jobs.size() - 1) : 0;
    RqSlzJobManager job = jobs.get(index);
    String postfix =
        !job.getReportType().equalsIgnoreCase(job.getContexts().get(0))
            ? "/" + job.getContexts().get(0)
            : "";
    String path =
        IsaCommonMethods.resolvePattern(
                EnSlzSpotifyApiEps.V1_ANALYTICS_PATTERN.get(),
                new HashMap<String, String>() {
                  {
                      put(
                        "prefix",
                          Arrays.stream(EnSlzSpotifyApiResources.values())
                              .filter(o -> o.name().equalsIgnoreCase(job.getLicensor()))
                              .collect(Collectors.toList())
                              .get(0)
                              .prefix());
                    put("resource", job.getReportType());
                    String[] dateTokens =
                        IsaCommonMethods.printDateTimeText(DT_NOW.minusDays(10), "yyyy-MM-dd")
                            .split("-");
                    put("year", dateTokens[0]);
                    put("month", dateTokens[1]);
                    put("day", dateTokens[2]);
                  }
                })
            + postfix;
    byte[] bytes =
        delphi
            .api()
            .rest()
            .spotifyApi(true)
            .withHeaders(
                new HashMap<String, Object>() {
                  {
                    put("Authorization", "Bearer " + authToken.getAccessToken());
                    put("content-encoding", "gzip");
                    put("response-content-disposition", "attachment");
                  }
                })
            //                            .withBody(body)
            .execGet(path)
            .withThen()
            .withValidatableRs()
            .statusCode(
                AnyOf.anyOf(Matchers.is(200), Matchers.is(400), Matchers.is(404)))
            .extract()
            .asByteArray();
    IsaCommonMethods.writeStreamToFile(
        bytes, new File("build/"), reportNameText, DT_NOW.getMillis() + "-details.txt.gz");
  }

  @Issue("DAE-803")
  @Test
  @Parameters({"reportNameText"})
  public void tc2_whenReportDateCurrentDay_thenStatusCodeAnyOfValid(
      @Optional("spotify-sme-streams-v4") String reportNameText) {
    Map<String, String> secretOAuth = fetchAwsSecret(EnAwsSecrets.DELPHI_SLZ_SPOTIFY_V2);
    RsSpotifyApiToken authToken =
        delphi
            .api()
            .rest()
            .spotifyApi(false)
            .withFormParams(
                new HashMap<String, Object>() {
                  {
                    put("grant_type", "client_credentials");
                    put("client_id", secretOAuth.get("client_id"));
                    put("client_secret", secretOAuth.get("client_secret"));
                  }
                })
            .execPost(EnSlzSpotifyApiEps.AUTH.get())
            .withThen()
            .withValidatableRs()
            .statusCode(200)
            .extract()
            .as(RsSpotifyApiToken.class, ObjectMapperType.GSON);
    List<RqSlzJobManager> jobs = delphi.fs().listSfRqSlzMainFlow(reportNameText);
    int index = jobs.size() > 1 ? IsaCommonMethods.random.nextInt(jobs.size() - 1) : 0;
    RqSlzJobManager job = jobs.get(index);
    String path =
        IsaCommonMethods.resolvePattern(
                EnSlzSpotifyApiEps.V1_ANALYTICS_PATTERN.get(),
                new HashMap<String, String>() {
                  {
                    put(
                        "prefix",
                        Arrays.stream(EnSlzSpotifyApiResources.values())
                            .filter(o -> o.name().equalsIgnoreCase(job.getLicensor()))
                            .collect(Collectors.toList())
                            .get(0)
                            .prefix());
                    put("resource", job.getReportType());
                    String[] dateTokens =
                        IsaCommonMethods.printDateTimeText(DT_NOW.minusDays(0), "yyyy-MM-dd")
                            .split("-");
                    put("year", dateTokens[0]);
                    put("month", dateTokens[1]);
                    put("day", dateTokens[2]);
                  }
                })
            + (!job.getReportType().equalsIgnoreCase(job.getContexts().get(0))
                ? "/" + job.getContexts().get(0)
                : "");
    byte[] bytes =
        delphi
            .api()
            .rest()
            .spotifyApi(true)
            .withHeaders(
                new HashMap<String, Object>() {
                  {
                    put("Authorization", "Bearer " + authToken.getAccessToken());
                  }
                })
            .withBody(String.format("{\"version\":\"%s\"}", job.getVersion()))
            .execGet(path)
            .withThen()
            .withValidatableRs()
            .statusCode(
                AnyOf.anyOf(Matchers.is(200), Matchers.is(400), Matchers.is(404)))
            .extract()
            .asByteArray();
    IsaCommonMethods.writeStreamToFile(
        bytes, new File("build/"), reportNameText, DT_NOW.getMillis() + "-details.txt.gz");
  }
}
