package skilldesk.controller;

import io.micronaut.http.HttpStatus;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Delete;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.annotation.Put;
import io.micronaut.http.annotation.Status;
import io.micronaut.http.exceptions.HttpStatusException;
import skilldesk.entity.Message;
import skilldesk.mapper.MessageRepository;

import java.util.List;
import java.util.Map;

@Controller("/api")
public class MessageController {

    private final MessageRepository messageRepository;

    public MessageController(MessageRepository messageRepository) {
        this.messageRepository = messageRepository;
    }

    @Get("/message")
    public Map<String, String> getMessage() {
        Message message = messageRepository.findFirst();
        if (message == null) {
            throw new HttpStatusException(HttpStatus.NOT_FOUND, "Message not found");
        }
        return Map.of("message", message.getContent());
    }

    @Get("/messages")
    public List<Message> listMessages() {
        return messageRepository.findAll();
    }

    @Post("/messages")
    @Status(HttpStatus.CREATED)
    public Message createMessage(@Body Map<String, String> body) {
        String content = body.get("content");
        if (content == null || content.strip().isEmpty()) {
            throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Content must not be empty");
        }
        Message message = new Message(content.strip());
        messageRepository.insert(message);
        return message;
    }

    @Put("/messages/{id}")
    public Message updateMessage(Integer id, @Body Map<String, String> body) {
        String content = body.get("content");
        if (content == null || content.strip().isEmpty()) {
            throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Content must not be empty");
        }
        int updated = messageRepository.update(id, content.strip());
        if (updated == 0) {
            throw new HttpStatusException(HttpStatus.NOT_FOUND, "Message not found");
        }
        return new Message(id, content.strip());
    }

    @Delete("/messages/{id}")
    public Map<String, Boolean> deleteMessage(Integer id) {
        int deleted = messageRepository.deleteById(id);
        if (deleted == 0) {
            throw new HttpStatusException(HttpStatus.NOT_FOUND, "Message not found");
        }
        return Map.of("success", true);
    }
}
