using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using SimpleLIS.DTO;
using SimpleLIS.Models;
using SimpleLIS.Services;

namespace SimpleLIS.Controllers;

[ApiController]
[Route("api/messages")]
public class MessagesController : ControllerBase
{
    private readonly MessageService _messageService;
    private readonly IMapper _mapper;

    public MessagesController(MessageService messageService, IMapper mapper)
    {
        _messageService = messageService;
        _mapper = mapper;
    }

    [HttpPost]
    public async Task<IActionResult> CreateMessage([FromBody] MessageDTO messageDto)
    {
        if (!ModelState.IsValid) return BadRequest(ModelState);

        var message = _mapper.Map<Message>(messageDto);
        var createdMessage = await _messageService.CreateMessageAsync(message);

        var createdMessageDto = _mapper.Map<MessageDTO>(createdMessage);
        return Ok(createdMessageDto);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetMessage(int id)
    {
        var message = await _messageService.GetMessageByIdAsync(id);
        if (message == null) return NotFound();

        var messageDto = _mapper.Map<MessageDTO>(message);
        return Ok(messageDto);
    }

    [HttpGet]
    public async Task<IActionResult> ListMessages()
    {
        var messages = await _messageService.ListMessagesAsync();
        var messagesDto = _mapper.Map<IEnumerable<MessageDTO>>(messages);

        return Ok(messagesDto);
    }

    // PUT: api/Messages/{id}
    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateMessage(int id, [FromBody] MessageDTO messageDto)
    {
        if (!ModelState.IsValid) return BadRequest(ModelState);

        if (!await _messageService.MessageExistsAsync(id))
        {
            return NotFound();
        }

        var message = _mapper.Map<Message>(messageDto);
        message.MessageId = id; // Ensure the correct ID is used

        var updatedMessage = await _messageService.UpdateMessageAsync(message);
        var updatedMessageDto = _mapper.Map<MessageDTO>(updatedMessage);

        return Ok(updatedMessageDto);
    }

    // DELETE: api/Messages/{id}
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteMessage(int id)
    {
        var deleted = await _messageService.DeleteMessageAsync(id);
        if (!deleted) return NotFound();

        return NoContent();
    }
}
