package com.petshop.backend.controller;

import com.petshop.backend.entity.User;
import com.petshop.backend.repository.UserRepository;
import com.petshop.backend.service.AvatarStorageService;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
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 java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

    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 || !avatarStorageService.hasAvatar(user)) {
            return ResponseEntity.notFound().build();
        }

        try {
            Resource resource = avatarStorageService.loadAvatarResource(user);
            return ResponseEntity.ok()
                    .contentType(avatarStorageService.resolveMediaType(user))
                    .body(resource);
        } catch (IllegalArgumentException ex) {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/{userId}/avatar")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> uploadUserAvatar(@PathVariable Long userId, @RequestParam("avatar") MultipartFile file) {
        User user = userRepository.findById(userId).orElse(null);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        if (file.isEmpty()) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "Please select a file to upload");
            return ResponseEntity.badRequest().body(error);
        }

        if (file.getSize() > 5 * 1024 * 1024) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "File size must not exceed 5MB");
            return ResponseEntity.badRequest().body(error);
        }

        String contentType = file.getContentType();
        if (contentType == null || (!contentType.equals("image/jpeg") && !contentType.equals("image/png") && !contentType.equals("image/gif"))) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "Only JPG, PNG, and GIF images are allowed");
            return ResponseEntity.badRequest().body(error);
        }

        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) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "Failed to upload avatar: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    @DeleteMapping("/{userId}/avatar")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteUserAvatar(@PathVariable Long userId) {
        User user = userRepository.findById(userId).orElse(null);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        try {
            avatarStorageService.deleteAvatar(user);
            user.setAvatarUrl(null);
            userRepository.save(user);
            Map<String, String> result = new HashMap<>();
            result.put("message", "Avatar removed successfully");
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "Failed to remove avatar: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
}
