/*
 * Handles customers viewing and managing their own pets.
 *
 * Author: Harkamal
 * Date: April 2026
 */
package com.petshop.backend.controller;

import com.petshop.backend.dto.pet.MyPetRequest;
import com.petshop.backend.dto.pet.MyPetResponse;
import com.petshop.backend.service.PetService;
import com.petshop.backend.util.AuthenticationHelper;
import jakarta.validation.Valid;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
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.List;

@RestController
@RequestMapping("/api/v1/my-pets")
@PreAuthorize("isAuthenticated()")
public class MyPetController {

    private final PetService petService;

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

    @GetMapping
    public ResponseEntity<List<MyPetResponse>> getMyPets(@RequestParam(required = false) String status) {
        return ResponseEntity.ok(petService.getMyPets(AuthenticationHelper.getAuthenticatedUserId(), status));
    }

    @PostMapping
    public ResponseEntity<MyPetResponse> createMyPet(@Valid @RequestBody MyPetRequest request) {
        return ResponseEntity.ok(petService.createMyPet(AuthenticationHelper.getAuthenticatedUserId(), request));
    }

    @PutMapping("/{id}")
    public ResponseEntity<MyPetResponse> updateMyPet(@PathVariable Long id, @Valid @RequestBody MyPetRequest request) {
        return ResponseEntity.ok(petService.updateMyPet(AuthenticationHelper.getAuthenticatedUserId(), id, request));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteMyPet(@PathVariable Long id) {
        petService.deleteMyPet(AuthenticationHelper.getAuthenticatedUserId(), id);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/{id}/image")
    public ResponseEntity<MyPetResponse> uploadMyPetImage(@PathVariable Long id, @RequestParam("image") MultipartFile image) throws IOException {
        return ResponseEntity.ok(petService.uploadMyPetImage(AuthenticationHelper.getAuthenticatedUserId(), id, image));
    }
}
