package com.petshop.backend.controller;

import com.petshop.backend.entity.User;
import com.petshop.backend.exception.ResourceNotFoundException;
import com.petshop.backend.repository.UserRepository;
import com.petshop.backend.service.EmailService;
import com.petshop.backend.util.AuthenticationHelper;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/contact")
public class ContactController {

    private final EmailService emailService;
    private final UserRepository userRepository;

    public ContactController(EmailService emailService, UserRepository userRepository) {
        this.emailService = emailService;
        this.userRepository = userRepository;
    }

    public record ContactRequest(
        @NotBlank @Size(max = 150) String subject,
        @NotBlank @Size(max = 2000) String body
    ) {}

    @PostMapping
    public ResponseEntity<Void> sendContactEmail(@Valid @RequestBody ContactRequest req) {
        Long userId = AuthenticationHelper.getAuthenticatedUserId();
        User user = userRepository.findById(userId).orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + userId));
        emailService.sendContactMessage(user, req.subject(), req.body());
        return ResponseEntity.ok().build();
    }
}
