package com.petshop.backend.service;

import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class ChatAttachmentStorageService {

    private static final String STORED_PREFIX = "/uploads/chat/";
    private final Path chatDirectory = Paths.get("uploads", "chat").toAbsolutePath().normalize();

    public String storeAttachment(MultipartFile file) throws IOException {
        Files.createDirectories(chatDirectory);

        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        
        String filename = UUID.randomUUID() + extension;
        Path filePath = chatDirectory.resolve(filename).normalize();

        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        return STORED_PREFIX + filename;
    }

    public Resource loadAttachmentResource(String attachmentUrl) {
        Path filePath = resolveStoredPath(attachmentUrl);
        if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
            throw new IllegalArgumentException("Attachment file was not found");
        }
        return new PathResource(filePath);
    }

    public MediaType resolveMediaType(String attachmentUrl) {
        try {
            return MediaTypeFactory.getMediaType(loadAttachmentResource(attachmentUrl)).orElse(MediaType.APPLICATION_OCTET_STREAM);
        } catch (IllegalArgumentException ex) {
            return MediaType.APPLICATION_OCTET_STREAM;
        }
    }

    private Path resolveStoredPath(String attachmentUrl) {
        if (attachmentUrl == null || attachmentUrl.isBlank() || !attachmentUrl.startsWith(STORED_PREFIX)) {
            throw new IllegalArgumentException("Invalid attachment URL");
        }

        String filename = attachmentUrl.substring(STORED_PREFIX.length());
        if (filename.isBlank() || filename.contains("/") || filename.contains("\\") || filename.contains("..")) {
            throw new IllegalArgumentException("Invalid attachment filename");
        }

        Path resolved = chatDirectory.resolve(filename).normalize();
        if (!resolved.startsWith(chatDirectory)) {
            throw new IllegalArgumentException("Invalid attachment path");
        }
        return resolved;
    }
}
