package com.petshop.backend.service;

import com.petshop.backend.entity.User;
import org.springframework.beans.factory.annotation.Value;
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 jakarta.annotation.PostConstruct;
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.Locale;
import java.util.UUID;

@Service
public class AvatarStorageService {

    private static final String STORED_PREFIX = "/uploads/avatars/";
    private static final String OWNER_ENDPOINT = "/api/v1/auth/me/avatar/file";

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

    private Path avatarDirectory;

    @PostConstruct
    private void init() {
        avatarDirectory = Paths.get(uploadBaseDir, "avatars").toAbsolutePath().normalize();
    }

    public String storeAvatar(MultipartFile file) throws IOException {
        Files.createDirectories(avatarDirectory);

        String originalFilename = file.getOriginalFilename();
        String extension = resolveExtension(originalFilename);
        String filename = UUID.randomUUID() + extension;
        Path filePath = avatarDirectory.resolve(filename).normalize();

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

    public Resource loadAvatarResource(User user) {
        Path filePath = resolveStoredAvatarPath(user.getAvatarUrl());
        if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
            throw new IllegalArgumentException("Avatar file was not found");
        }
        return new PathResource(filePath);
    }

    public void deleteAvatar(User user) throws IOException {
        if (user.getAvatarUrl() == null || user.getAvatarUrl().isBlank()) {
            return;
        }
        try {
            Files.deleteIfExists(resolveStoredAvatarPath(user.getAvatarUrl()));
        } catch (IllegalArgumentException ignored) {
        }
    }

    public String toOwnerAvatarUrl(User user) {
        return hasAvatar(user) ? OWNER_ENDPOINT : null;
    }

    public String toStoredAvatarUrl(String avatarFilenamePath) {
        return avatarFilenamePath;
    }

    public boolean hasAvatar(User user) {
        return user.getAvatarUrl() != null && !user.getAvatarUrl().isBlank();
    }

    public MediaType resolveMediaType(User user) {
        try {
            return MediaTypeFactory.getMediaType(loadAvatarResource(user)).orElse(MediaType.APPLICATION_OCTET_STREAM);
        } catch (IllegalArgumentException ex) {
            return MediaType.APPLICATION_OCTET_STREAM;
        }
    }

    private Path resolveStoredAvatarPath(String storedAvatarUrl) {
        if (storedAvatarUrl == null || storedAvatarUrl.isBlank() || !storedAvatarUrl.startsWith(STORED_PREFIX)) {
            throw new IllegalArgumentException("Avatar file was not found");
        }

        String filename = storedAvatarUrl.substring(STORED_PREFIX.length());
        if (filename.isBlank() || filename.contains("/") || filename.contains("\\") || filename.contains("..")) {
            throw new IllegalArgumentException("Avatar file was not found");
        }

        Path resolved = avatarDirectory.resolve(filename).normalize();
        if (!resolved.startsWith(avatarDirectory)) {
            throw new IllegalArgumentException("Avatar file was not found");
        }
        return resolved;
    }

    private String resolveExtension(String originalFilename) {
        if (originalFilename == null) {
            return ".jpg";
        }
        int extensionIndex = originalFilename.lastIndexOf('.');
        if (extensionIndex < 0 || extensionIndex == originalFilename.length() - 1) {
            return ".jpg";
        }
        String extension = originalFilename.substring(extensionIndex).toLowerCase(Locale.ROOT);
        return switch (extension) {
            case ".jpg", ".jpeg", ".png", ".gif", ".webp" -> extension;
            default -> ".jpg";
        };
    }
}
