package dev.sonpx.loyalty.agent.controller;

import dev.sonpx.loyalty.agent.domain.Conversation;
import dev.sonpx.loyalty.agent.domain.Message;
import dev.sonpx.loyalty.agent.dto.ConversationSummaryDto;
import dev.sonpx.loyalty.agent.repository.ConversationRepository;
import dev.sonpx.loyalty.agent.repository.MessageRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;


@RestController
@RequestMapping("/api/v1/conversations")
@CrossOrigin(origins = "*")
public class ConversationController {

    private final ConversationRepository conversationRepository;
    private final MessageRepository messageRepository;

    public ConversationController(ConversationRepository conversationRepository, MessageRepository messageRepository) {
        this.conversationRepository = conversationRepository;
        this.messageRepository = messageRepository;
    }

    @GetMapping
    @Transactional
    public ResponseEntity<List<ConversationSummaryDto>> getConversations() {
        List<Conversation> conversations = conversationRepository.findAllByOrderByUpdatedAtDesc();
        List<ConversationSummaryDto> dtos = new ArrayList<>();

        for (Conversation c : conversations) {
            List<Message> messages = messageRepository.findByConversationIdOrderByCreatedAtAsc(c.getId());

            // Clean up empty conversations from DB (except if it's the only one and newly created)
            if (messages.isEmpty()) {
                conversationRepository.delete(c);
                continue;
            }

            String title = c.getTitle();
            if (title == null || title.isBlank() || "Cuộc trò chuyện mới".equalsIgnoreCase(title)) {
                Optional<Message> firstUserMsg = messages.stream()
                        .filter(m -> "USER".equalsIgnoreCase(m.getRole()))
                        .findFirst();
                if (firstUserMsg.isPresent()) {
                    String content = firstUserMsg.get().getContent();
                    title = content.length() > 40 ? content.substring(0, 40) + "..." : content;
                } else {
                    title = "Cuộc trò chuyện mới";
                }
            }

            String preview = "";
            Message lastMsg = messages.getLast();
            String content = lastMsg.getContent();
            preview = content.length() > 100 ? content.substring(0, 100) + "..." : content;

            dtos.add(ConversationSummaryDto.builder()
                    .id(c.getId())
                    .title(title)
                    .preview(preview)
                    .createdAt(c.getCreatedAt())
                    .updatedAt(c.getUpdatedAt())
                    .build());
        }

        return ResponseEntity.ok(dtos);
    }

    @PostMapping
    public ResponseEntity<Conversation> createConversation() {
        Conversation conversation = new Conversation();
        conversation.setId(UUID.randomUUID().toString());
        conversation.setTitle("Cuộc trò chuyện mới");
        conversation.setCreatedAt(Instant.now());
        conversation.setUpdatedAt(Instant.now());
        Conversation saved = conversationRepository.save(conversation);
        return ResponseEntity.ok(saved);
    }

    @GetMapping("/{id}/messages")
    public ResponseEntity<List<Message>> getMessages(@PathVariable("id") String id) {
        List<Message> messages = messageRepository.findByConversationIdOrderByCreatedAtAsc(id);
        return ResponseEntity.ok(messages);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ConversationSummaryDto> updateTitle(
            @PathVariable("id") String id,
            @RequestBody Map<String, String> payload) {
        String newTitle = payload.get("title");
        if (newTitle == null || newTitle.isBlank()) {
            return ResponseEntity.badRequest().build();
        }

        return conversationRepository.findById(id).map(conv -> {
            conv.setTitle(newTitle.trim());
            conv.setUpdatedAt(Instant.now());
            Conversation saved = conversationRepository.save(conv);

            List<Message> messages = messageRepository.findByConversationIdOrderByCreatedAtAsc(id);
            String preview = "";
            if (!messages.isEmpty()) {
                String content = messages.getLast().getContent();
                preview = content.length() > 100 ? content.substring(0, 100) + "..." : content;
            }

            return ResponseEntity.ok(ConversationSummaryDto.builder()
                    .id(saved.getId())
                    .title(saved.getTitle())
                    .preview(preview)
                    .createdAt(saved.getCreatedAt())
                    .updatedAt(saved.getUpdatedAt())
                    .build());
        }).orElseGet(() -> ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    @Transactional
    public ResponseEntity<Void> deleteConversation(@PathVariable("id") String id) {
        List<Message> messages = messageRepository.findByConversationIdOrderByCreatedAtAsc(id);
        if (!messages.isEmpty()) {
            messageRepository.deleteAll(messages);
        }
        conversationRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}


