package app.mealsmadeeasy.api.util;

import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class MimeTypeService {

    private static final Pattern extensionPattern = Pattern.compile(".+\\.(.+)$");

    private static final String IMAGE_JPEG =  "image/jpeg";
    private static final String IMAGE_PNG = "image/png";
    private static final String IMAGE_SVG = "image/svg+xml";
    private static final String IMAGE_WEBP = "image/webp";

    public String getMimeType(String userFilename) {
        final Matcher m = extensionPattern.matcher(userFilename);
        if (m.matches()) {
            final String extension = m.group(1);
            return switch (extension.toLowerCase()) {
                case "jpg", "jpeg" -> IMAGE_JPEG;
                case "png" -> IMAGE_PNG;
                case "svg" -> IMAGE_SVG;
                case "webp" -> IMAGE_WEBP;
                default -> throw new IllegalArgumentException("Cannot determine mime type for extension: " + extension);
            };
        } else {
            throw new IllegalArgumentException("Cannot determine mime type for filename: " + userFilename);
        }
    }

    public String getExtension(String mimeType) {
        return switch (mimeType.toLowerCase()) {
            case IMAGE_JPEG -> "jpg";
            case IMAGE_PNG -> "png";
            case IMAGE_SVG -> "svg";
            case IMAGE_WEBP -> "webp";
            default -> throw new IllegalArgumentException(
                    "Cannot determine extension from given mimetype: " + mimeType
            );
        };
    }

}
