/*
 * Copyright (c) 2023 Airbyte, Inc., all rights reserved.
 */

package io.airbyte.config.helpers;

import static org.junit.jupiter.api.Assertions.assertEquals;

import com.google.cloud.storage.Storage;
import io.airbyte.config.EnvConfigs;
import io.airbyte.config.storage.CloudStorageConfigs;
import io.airbyte.config.storage.DefaultGcsClientFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Slf4j
@Tag("logger-client")
class GcsLogsTest {

  private static Storage getClientFactory() {
    return new DefaultGcsClientFactory(new CloudStorageConfigs.GcsConfig(
        System.getenv(LogClientSingleton.GCS_LOG_BUCKET),
        System.getenv(LogClientSingleton.GOOGLE_APPLICATION_CREDENTIALS))).get();
  }

  /**
   * The test files here were generated by {@link S3LogsTest}. See that class for more information.
   *
   * Generate enough files to force pagination and confirm all data is read.
   */
  @Test
  void testRetrieveAllLogs() throws IOException {
    final File data;
    data = GcsLogs.getFile(getClientFactory(), (new EnvConfigs()).getLogConfigs(), "paginate", 6);
    final var retrieved = new ArrayList<String>();
    Files.lines(data.toPath()).forEach(retrieved::add);

    final var expected = List.of("Line 0", "Line 1", "Line 2", "Line 3", "Line 4", "Line 5", "Line 6", "Line 7", "Line 8");

    assertEquals(expected, retrieved);

  }

  /**
   * The test files for this test have been pre-generated and uploaded into the bucket folder. The
   * folder contains the following files with these contents:
   * <li>first-file.txt - Line 1, Line 2, Line 3</li>
   * <li>second-file.txt - Line 4, Line 5, Line 6</li>
   * <li>third-file.txt - Line 7, Line 8, Line 9</li>
   */
  @Test
  void testTail() throws IOException {
    final var data = new GcsLogs(GcsLogsTest::getClientFactory).tailCloudLog((new EnvConfigs()).getLogConfigs(), "tail", 6);

    final var expected = List.of("Line 4", "Line 5", "Line 6", "Line 7", "Line 8", "Line 9");
    assertEquals(data, expected);
  }

}
