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.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@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("hasAnyRole('STAFF', 'ADMIN')")
    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();
        }
    }
}
