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

import com.petshop.backend.dto.pet.PetResponse;
import com.petshop.backend.entity.User;
import com.petshop.backend.service.PetService;
import com.petshop.backend.util.AuthenticationHelper;
import org.springframework.core.io.Resource;
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.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/v1/pets")
public class PetImageController {

    private final PetService petService;

    public PetImageController(PetService petService) {
        this.petService = petService;
    }

    @PostMapping("/{id}/image")
    @PreAuthorize("hasAnyRole('STAFF', 'ADMIN')")
    public ResponseEntity<PetResponse> uploadPetImage(@PathVariable Long id, @RequestParam("image") MultipartFile image) throws IOException {
        return ResponseEntity.ok(petService.uploadPetImage(id, image));
    }

    @GetMapping("/{id}/image")
    public ResponseEntity<Resource> getPetImage(@PathVariable Long id) {
        Long userId = null;
        User.Role role = null;
        try {
            userId = AuthenticationHelper.getAuthenticatedUserId();
            role = AuthenticationHelper.getAuthenticatedRole();
        } catch (Exception ignored) {
        }
        PetService.ImagePayload payload = petService.loadPetImage(id, userId, role);
        return ResponseEntity.ok().contentType(payload.mediaType()).body(payload.resource());
    }

    @DeleteMapping("/{id}/image")
    @PreAuthorize("hasAnyRole('STAFF', 'ADMIN')")
    public ResponseEntity<PetResponse> deletePetImage(@PathVariable Long id) {
        return ResponseEntity.ok(petService.deletePetImage(id));
    }
}
