package com.petshop.backend.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
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 static final String BLOB_CONTAINER = "chat";

    @Value("${app.upload.base-dir:uploads}")
    private String uploadBaseDir;

    @Autowired
    private AzureBlobService blobService;

    public String storeAttachment(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = (originalFilename != null && originalFilename.contains("."))
                ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
        String filename = UUID.randomUUID() + extension;

        if (blobService.isEnabled()) {
            blobService.upload(BLOB_CONTAINER, filename, file.getBytes());
        } else {
            Path chatDirectory = Paths.get(uploadBaseDir, "chat").toAbsolutePath().normalize();
            Files.createDirectories(chatDirectory);
            Files.copy(file.getInputStream(), chatDirectory.resolve(filename).normalize(), StandardCopyOption.REPLACE_EXISTING);
        }
        return STORED_PREFIX + filename;
    }

    public Resource loadAttachmentResource(String attachmentUrl) {
        String filename = extractFilename(attachmentUrl);
        if (blobService.isEnabled()) {
            return new ByteArrayResource(blobService.download(BLOB_CONTAINER, filename));
        }
        Path chatDirectory = Paths.get(uploadBaseDir, "chat").toAbsolutePath().normalize();
        Path filePath = chatDirectory.resolve(filename).normalize();
        if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
            throw new IllegalArgumentException("Attachment file was not found");
        }
        return new PathResource(filePath);
    }

    public MediaType resolveMediaType(String attachmentUrl) {
        String filename = extractFilename(attachmentUrl);
        return MediaTypeFactory.getMediaType(filename).orElse(MediaType.APPLICATION_OCTET_STREAM);
    }

    private String extractFilename(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");
        }
        return filename;
    }
}
