package com.petshop.backend.controller;

import com.petshop.backend.dto.ai.AiChatRequest;
import com.petshop.backend.dto.ai.AiChatResponse;
import com.petshop.backend.entity.Pet;
import com.petshop.backend.entity.User;
import com.petshop.backend.repository.PetRepository;
import com.petshop.backend.repository.UserRepository;
import com.petshop.backend.service.OpenRouterService;
import com.petshop.backend.util.AuthenticationHelper;
import com.petshop.backend.util.ContentFilter;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/api/v1/ai-chat")
public class AiChatController {

    private final OpenRouterService openRouterService;
    private final PetRepository petRepository;
    private final UserRepository userRepository;

    public AiChatController(OpenRouterService openRouterService,
                            PetRepository petRepository,
                            UserRepository userRepository) {
        this.openRouterService = openRouterService;
        this.petRepository = petRepository;
        this.userRepository = userRepository;
    }

    private User getCurrentUser() {
        try {
            return AuthenticationHelper.getAuthenticatedUser(userRepository);
        } 
        
        catch (RuntimeException ex) {
            throw new UsernameNotFoundException(ex.getMessage(), ex);
        }
    }

    @PostMapping("/message")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<AiChatResponse> sendMessage(@Valid @RequestBody AiChatRequest request) {
        if (request.getMessage() == null || request.getMessage().isBlank()) {
            return ResponseEntity.badRequest().body(AiChatResponse.fail("Message cannot be empty"));
        }
        ContentFilter.validate(request.getMessage());

        User user = getCurrentUser();

        List<Pet> userPets;
        try {
            userPets = petRepository.findAllByOwner_IdAndPetStatusInOrderByPetNameAsc(
                    user.getId(), List.of("Adopted", "Owned"));
        } 
        
        catch (Exception e) {
            userPets = Collections.emptyList();
        }

        try {
            String aiReply = openRouterService.chat(
                    request.getHistory(),
                    request.getMessage(),
                    userPets
            );

            return ResponseEntity.ok(AiChatResponse.ok(aiReply));
        } 
        
        catch (IllegalStateException e) {
            
            return ResponseEntity.status(503).body(AiChatResponse.fail("AI service is not configured. Please contact support."));
        } 
        
        catch (Exception e) {

            return ResponseEntity.status(502).body(AiChatResponse.fail("AI service is temporarily unavailable. Please try again later."));
        }
    }
}
