package dev.lions.utils;

import dev.lions.exceptions.ImageProcessingException;
import jakarta.enterprise.context.ApplicationScoped;
import java.awt.Graphics2D;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.UUID;
import javax.imageio.ImageIO;

@Slf4j
@ApplicationScoped
public class ImageProcessor {

  public String processAndStoreProjectImage(byte[] imageData, String projectTitle,
                                            String storagePath) {
    try {
      String fileName = generateUniqueFileName(projectTitle);
      BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));

      // Création des différentes tailles d'images
      BufferedImage thumbnail = resizeImage(originalImage, 300, 200);
      BufferedImage medium = resizeImage(originalImage, 800, 600);
      BufferedImage large = resizeImage(originalImage, 1920, 1080);

      // Sauvegarde des images
      String basePath = Path.of(storagePath, "projects").toString();
      saveImage(thumbnail, basePath, "thumb_" + fileName);
      saveImage(medium, basePath, "medium_" + fileName);
      saveImage(large, basePath, "large_" + fileName);

      return fileName;

    } catch (Exception e) {
      log.error("Error processing project image: {}", e.getMessage());
      throw new ImageProcessingException("Failed to process project image", e);
    }
  }

  private String generateUniqueFileName(String baseName) {
    String sanitizedName = baseName.replaceAll("[^a-zA-Z0-9]", "-").toLowerCase();
    return sanitizedName + "-" + UUID.randomUUID().toString().substring(0, 8) + ".jpg";
  }

  private BufferedImage resizeImage(BufferedImage originalImage, int targetWidth,
                                    int targetHeight) {
    BufferedImage resizedImage =
        new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = resizedImage.createGraphics();
    graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
    graphics2D.dispose();
    return resizedImage;
  }

  private void saveImage(BufferedImage image, String directoryPath, String fileName)
      throws IOException {
    File directory = new File(directoryPath);
    if (!directory.exists()) {
      directory.mkdirs();
    }

    File outputFile = new File(directory, fileName);
    ImageIO.write(image, "JPEG", outputFile);
  }
}

