package com.airlock.iam.base.misc.file;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import jakarta.annotation.Nullable;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

public final class FileName {
   private static final Pattern UNSAFE_FILE_COMPONENT = Pattern.compile("[^a-zA-Z0-9_\\-]");
   private static final String SAFE_FILE_COMPONENT_REPLACEMENT = "_";
   private static final String DEFAULT_DELIMITER = "-";
   private final String value;

   private FileName(
      @Nullable CharSequence delimiter, @Nullable CharSequence prefix, boolean delimiterAfterPrefix, @Nullable CharSequence suffix, List<String> elements
   ) {
      CharSequence fileNameDelimiter = Optional.ofNullable(delimiter).orElse("-");
      String fileNamePrefix = Optional.ofNullable(prefix).map(p -> p.toString() + (delimiterAfterPrefix ? fileNameDelimiter : "")).orElse("");
      CharSequence fileNameSuffix = Optional.ofNullable(suffix).orElse("");
      String filename = elements.stream()
         .<String>map(StringUtils::strip)
         .filter(StringUtils::isNotBlank)
         .map(FileName::sanitizeFileComponent)
         .collect(Collectors.joining(fileNameDelimiter, fileNamePrefix, fileNameSuffix));
      validateFileName(filename);
      this.value = filename;
   }

   private static void validateFileName(@Nullable String filename) {
      Validate.notBlank(filename);
      Path path = Paths.get(filename);
      Validate.isTrue(path.getNameCount() == 1, "File name '%s' is invalid: it contains multiple path elements.", new Object[]{filename});
      Validate.isTrue(!path.isAbsolute(), "File name '%s' is invalid: it represents an absolute path.", new Object[]{filename});
   }

   private static String sanitizeFileComponent(CharSequence fileNameComponent) {
      return UNSAFE_FILE_COMPONENT.matcher(fileNameComponent).replaceAll("_");
   }

   public FileName append(CharSequence newSuffix) {
      return builder().prefix(this.value).suffix(newSuffix).build();
   }

   @Override
   public String toString() {
      return this.value;
   }

   @SuppressFBWarnings(justification = "generated code")
   public static FileName.FileNameBuilder builder() {
      return new FileName.FileNameBuilder();
   }

   @SuppressFBWarnings(justification = "generated code")
   @Override
   public boolean equals(Object o) {
      if (o == this) {
         return true;
      } else if (!(o instanceof FileName other)) {
         return false;
      } else {
         Object this$value = this.value;
         Object other$value = other.value;
         return this$value == null ? other$value == null : this$value.equals(other$value);
      }
   }

   @SuppressFBWarnings(justification = "generated code")
   @Override
   public int hashCode() {
      int PRIME = 59;
      int result = 1;
      Object $value = this.value;
      return result * 59 + ($value == null ? 43 : $value.hashCode());
   }

   @SuppressFBWarnings(justification = "generated code")
   public String value() {
      return this.value;
   }

   @SuppressFBWarnings(justification = "generated code")
   public static class FileNameBuilder {
      @SuppressFBWarnings(justification = "generated code")
      private CharSequence delimiter;
      @SuppressFBWarnings(justification = "generated code")
      private CharSequence prefix;
      @SuppressFBWarnings(justification = "generated code")
      private boolean delimiterAfterPrefix;
      @SuppressFBWarnings(justification = "generated code")
      private CharSequence suffix;
      @SuppressFBWarnings(justification = "generated code")
      private ArrayList<String> elements;

      @SuppressFBWarnings(justification = "generated code")
      FileNameBuilder() {
      }

      @SuppressFBWarnings(justification = "generated code")
      public FileName.FileNameBuilder delimiter(@Nullable CharSequence delimiter) {
         this.delimiter = delimiter;
         return this;
      }

      @SuppressFBWarnings(justification = "generated code")
      public FileName.FileNameBuilder prefix(@Nullable CharSequence prefix) {
         this.prefix = prefix;
         return this;
      }

      @SuppressFBWarnings(justification = "generated code")
      public FileName.FileNameBuilder delimiterAfterPrefix(boolean delimiterAfterPrefix) {
         this.delimiterAfterPrefix = delimiterAfterPrefix;
         return this;
      }

      @SuppressFBWarnings(justification = "generated code")
      public FileName.FileNameBuilder suffix(@Nullable CharSequence suffix) {
         this.suffix = suffix;
         return this;
      }

      @SuppressFBWarnings(justification = "generated code")
      public FileName.FileNameBuilder element(String element) {
         if (this.elements == null) {
            this.elements = new ArrayList<>();
         }

         this.elements.add(element);
         return this;
      }

      @SuppressFBWarnings(justification = "generated code")
      public FileName.FileNameBuilder elements(Collection<? extends String> elements) {
         if (elements == null) {
            throw new NullPointerException("elements cannot be null");
         }

         if (this.elements == null) {
            this.elements = new ArrayList<>();
         }

         this.elements.addAll(elements);
         return this;
      }

      @SuppressFBWarnings(justification = "generated code")
      public FileName.FileNameBuilder clearElements() {
         if (this.elements != null) {
            this.elements.clear();
         }

         return this;
      }

      @SuppressFBWarnings(justification = "generated code")
      public FileName build() {
         return new FileName(this.delimiter, this.prefix, this.delimiterAfterPrefix, this.suffix, switch (this.elements == null ? 0 : this.elements.size()) {
            case 0 -> Collections.emptyList();
            case 1 -> Collections.singletonList(this.elements.get(0));
            default -> Collections.unmodifiableList(new ArrayList<>(this.elements));
         });
      }

      @SuppressFBWarnings(justification = "generated code")
      @Override
      public String toString() {
         return "FileName.FileNameBuilder(delimiter="
            + this.delimiter
            + ", prefix="
            + this.prefix
            + ", delimiterAfterPrefix="
            + this.delimiterAfterPrefix
            + ", suffix="
            + this.suffix
            + ", elements="
            + this.elements
            + ")";
      }
   }
}
