/*
 * Handles uploading, retrieving, and deleting user profile pictures.
 *
 * Author: Harkamal
 * Date: April 2026
 */
package com.petshop.backend.controller;

import com.petshop.backend.entity.User;
import com.petshop.backend.exception.BusinessException;
import com.petshop.backend.exception.ResourceNotFoundException;
import com.petshop.backend.repository.UserRepository;
import com.petshop.backend.service.AvatarStorageService;
import com.petshop.backend.util.ImageValidationUtil;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/users")
public class UserAvatarController {

    private static final Logger log = LoggerFactory.getLogger(UserAvatarController.class);

    private final UserRepository userRepository;
    private final AvatarStorageService avatarStorageService;

    public UserAvatarController(UserRepository userRepository, AvatarStorageService avatarStorageService) {
        this.userRepository = userRepository;
        this.avatarStorageService = avatarStorageService;
    }

    @GetMapping("/{userId}/avatar/file")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<Resource> getUserAvatarFile(@PathVariable Long userId) {
        User user = userRepository.findById(userId).orElse(null);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        if (avatarStorageService.hasAvatar(user)) {
            try {
                Resource resource = avatarStorageService.loadAvatarResource(user);
                return ResponseEntity.ok()
                        .contentType(avatarStorageService.resolveMediaType(user))
                        .body(resource);
            } catch (IllegalArgumentException ignored) {
            }
        }

        return ResponseEntity.ok()
                .contentType(MediaType.valueOf("image/svg+xml"))
                .body(avatarStorageService.loadDefaultAvatarResource());
    }

    @PostMapping("/{userId}/avatar")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> uploadUserAvatar(@PathVariable Long userId, @RequestParam("avatar") MultipartFile file) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + userId));

        ImageValidationUtil.validate(file);

        try {
            avatarStorageService.deleteAvatar(user);
            String avatarPath = avatarStorageService.storeAvatar(file);
            user.setAvatarUrl(avatarPath);
            userRepository.save(user);

            Map<String, String> result = new HashMap<>();
            result.put("avatarUrl", avatarStorageService.toOwnerAvatarUrl(user));
            result.put("message", "Avatar uploaded successfully");
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            throw new BusinessException("Failed to upload avatar: " + e.getMessage());
        }
    }

    @DeleteMapping("/{userId}/avatar")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteUserAvatar(@PathVariable Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + userId));

        try {
            avatarStorageService.deleteAvatar(user);
        } catch (IOException e) {
            log.warn("Failed to delete avatar for user {}: {}", userId, e.getMessage());
        }
        user.setAvatarUrl(null);
        userRepository.save(user);

        Map<String, String> result = new HashMap<>();
        result.put("message", "Avatar removed successfully");
        return ResponseEntity.ok(result);
    }
}
