package tv.pluto;

import io.grpc.StatusRuntimeException;
import io.qameta.allure.TmsLink;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import lombok.SneakyThrows;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import tv.pluto.core.BaseTest;
import tv.pluto.grpc.categories.Categories;
import tv.pluto.grpc.categories.CategoriesClient;
import tv.pluto.grpc.categories.Category;
import tv.pluto.mongo.utils.CategoriesUtils;
import tv.pluto.utils.JsonUtils;

public class CategoriesTestSuite extends BaseTest {
  private String categories;
  private Categories category;
  private JsonUtils jsonUtils;
  private final String NON_EXISTING_CATEGORY = "NON_EXISTING_CATEGORY";

  private CategoriesUtils categoriesUtils;
  private CategoriesClient categoriesClient;

  @SneakyThrows
  @BeforeClass(alwaysRun = true)
  private void setUp() {
    jsonUtils = new JsonUtils();
    categories = Files.readString(Paths.get("src/main/resources/categories.json"));
    category = jsonUtils.fromJson(categories, Categories.class);
    categoriesUtils = new CategoriesUtils();
    categoriesClient = new CategoriesClient(grpcChannelManager.getChannel());
  }

  @Test
  @TmsLink("28500408")
  public void C28500408_TEST() {
    List<String> grpcCategories = categoriesClient.getCategories().getCategoriesList();
    Assert.assertEquals(categoriesUtils.getCategoriesFromAnnotations(), grpcCategories);
  }

  @Test
  @TmsLink("28500409")
  public void C28500409_TEST() throws InvocationTargetException, IllegalAccessException {
    List<Category> grpcCategoryList =
        categoriesUtils.toCategorySubCategoryMap(categoriesClient.getCategorySubCategoryMap());
    List<Category> categoryList = categoriesUtils.toSubCategoryMap(category);

    Assert.assertEquals(categoryList, grpcCategoryList);
  }

  @Test
  @TmsLink("28500410")
  public void C28500410_TEST() throws InvocationTargetException, IllegalAccessException {
    String randomCategory =
        categoriesUtils.getRandomItem(categoriesUtils.getCategoriesFromAnnotations());

    List<String> grpcSubCategories =
        categoriesClient.getSubCategoriesByCategory(randomCategory).getSubCategoriesList();
    List<String> subCategories =
        categoriesUtils.getSubCategoriesByAnnotation(randomCategory, category);

    Assert.assertEquals(subCategories, grpcSubCategories);
  }

  @Test(
      expectedExceptions = StatusRuntimeException.class,
      expectedExceptionsMessageRegExp =
          "NOT_FOUND: No sub categories found associated with category: "
              + NON_EXISTING_CATEGORY
              + "")
  @TmsLink("28500411")
  public void C28500411_TEST() {
    categoriesClient.getSubCategoriesByCategory(NON_EXISTING_CATEGORY);
  }
}
