package com.petshop.backend.controller;

import com.petshop.backend.dto.pet.PetResponse;
import com.petshop.backend.entity.User;
import com.petshop.backend.security.AppPrincipal;
import com.petshop.backend.service.PetService;
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.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
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;
import java.util.HashMap;
import java.util.Map;

@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<?> uploadPetImage(@PathVariable Long id, @RequestParam("image") MultipartFile image) {
        try {
            PetResponse response = petService.uploadPetImage(id, image);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException ex) {
            return badRequest(ex.getMessage());
        } catch (IOException ex) {
            return badRequest("Failed to upload pet image: " + ex.getMessage());
        }
    }

    @GetMapping("/{id}/image")
    public ResponseEntity<Resource> getPetImage(@PathVariable Long id) {
        PetService.ImagePayload payload = petService.loadPetImage(id, currentUserId(), currentUserRole());
        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));
    }

    private ResponseEntity<Map<String, String>> badRequest(String message) {
        Map<String, String> error = new HashMap<>();
        error.put("message", message);
        return ResponseEntity.badRequest().body(error);
    }

    private Long currentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof AppPrincipal appPrincipal) {
            return appPrincipal.getUserId();
        }
        return null;
    }

    private User.Role currentUserRole() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof AppPrincipal appPrincipal) {
            return appPrincipal.getRole();
        }
        return null;
    }
}
