package ai.decompile.workspace.service.storage;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Component
@Primary
public class LocalFileStorage implements FileStorage {
  private final Path baseDir;

  public LocalFileStorage(@Value("${app.storage.upload-dir}") String uploadDir) {
    this.baseDir = Path.of(uploadDir).toAbsolutePath().normalize();
  }

  @Override
  public String store(InputStream inputStream, String filename) throws IOException {
    Files.createDirectories(baseDir);

    var storedName = UUID.randomUUID() + "_" + filename;
    var targetPath = baseDir.resolve(storedName);
    Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);

    return storedName;
  }

  @Override
  public void delete(String path) throws IOException {
    var filePath = baseDir.resolve(path);
    Files.deleteIfExists(filePath);
  }

  @Override
  public InputStream read(String path) throws IOException {
    var filePath = baseDir.resolve(path);
    return Files.newInputStream(filePath);
  }

  @Override
  public String resolvePath(String path) {
    return baseDir.resolve(path).toAbsolutePath().normalize().toString();
  }
}
