package com.nebula.erp.product.service;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@Service
public class S3Service {

    @Autowired
    private AmazonS3 amazonS3;

    @Value("${s3.bucketName}")
    private String bucketName;

    public List<String> uploadMultipleFiles(List<MultipartFile> multipartFiles, String tenantName) {
        List<String> fileUrls = new ArrayList<>();

        multipartFiles.forEach(file -> {
            try {
                validateFile(file);
                File convertedFile = convertMultiPartToFile(file);
                String fileName = tenantName + "/" + generateFileName(file);
                String fileUrl = "https://" + bucketName + ".s3.amazonaws.com/" + fileName;

                // Upload to S3 without ACL
                amazonS3.putObject(new PutObjectRequest(bucketName, fileName, convertedFile));

                fileUrls.add(fileUrl);
                convertedFile.delete();
            } catch (Exception e) {
                throw new RuntimeException("Failed to upload file: " + file.getOriginalFilename(), e);
            }
        });

        return fileUrls;
    }

    public String uploadFile(MultipartFile multipartFile, String tenantName) {
        String fileUrl = "";
        try {
            validateFile(multipartFile);
            File file = convertMultiPartToFile(multipartFile);
            String fileName = tenantName + "/" + generateFileName(multipartFile);
            fileUrl = "https://" + bucketName + ".s3.amazonaws.com/" + fileName;
            uploadFileTos3bucket(fileName, file);
            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileUrl;
    }

    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("File is empty");
        }

        // Validate file type
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("Only image files are allowed");
        }

        // Validate file size (e.g., 5MB max)
        if (file.getSize() > 5 * 1024 * 1024) {
            throw new IllegalArgumentException("File size exceeds 5MB limit");
        }
    }

    private File convertMultiPartToFile(MultipartFile file) throws IOException {
        File convFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }

    private String generateFileName(MultipartFile multiPart) {
        return System.currentTimeMillis() + "-" + Objects.requireNonNull(multiPart.getOriginalFilename()).replace(" ", "_");
    }

    private void uploadFileTos3bucket(String fileName, File file) {
        try {
            amazonS3.putObject(new PutObjectRequest(bucketName, fileName, file));
        } catch (AmazonServiceException e) {
            throw new RuntimeException("Error uploading file to S3: " + e.getErrorMessage(), e);
        }
    }

    public void deleteFileFroms3bucket(String fileName) {
        try {
            // Extract the key from the URL
            String fileKey = fileName.substring(fileName.indexOf(".com/") + 5); // 5 = length of ".com/"
            amazonS3.deleteObject(bucketName, fileKey);
        } catch (AmazonServiceException e) {
            throw new RuntimeException("Error deleting file from S3: " + e.getErrorMessage(), e);
        }
    }
}