using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SIGCM.Domain.Entities;
using SIGCM.Domain.Interfaces;

namespace SIGCM.API.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class UserNotesController : ControllerBase
{
    private readonly IListingNoteRepository _noteRepo;

    public UserNotesController(IListingNoteRepository noteRepo)
    {
        _noteRepo = noteRepo;
    }

    [HttpGet("my-notes")]
    public async Task<IActionResult> GetMyNotes()
    {
        var userIdStr = User.FindFirst("Id")?.Value;
        if (string.IsNullOrEmpty(userIdStr) || !int.TryParse(userIdStr, out int userId))
            return Unauthorized();

        var notes = await _noteRepo.GetByUserIdAsync(userId);
        return Ok(notes);
    }

    [HttpGet("listing/{listingId}")]
    public async Task<IActionResult> GetByListing(int listingId)
    {
        var notes = await _noteRepo.GetByListingIdAsync(listingId);
        
        // Marcar como leídos los mensajes que SON de moderador para este usuario
        foreach (var note in notes.Where(n => n.IsFromModerator && !n.IsRead))
        {
            await _noteRepo.MarkAsReadAsync(note.Id);
        }
        
        return Ok(notes);
    }

    [HttpPost("listing/{listingId}/reply")]
    public async Task<IActionResult> Reply(int listingId, [FromBody] ReplyDto dto)
    {
        var userIdStr = User.FindFirst("Id")?.Value;
        if (string.IsNullOrEmpty(userIdStr) || !int.TryParse(userIdStr, out int userId))
            return Unauthorized();

        var note = new ListingNote
        {
            ListingId = listingId,
            SenderId = userId,
            IsFromModerator = false,
            Message = dto.Message
        };

        var id = await _noteRepo.CreateAsync(note);
        return Ok(new { id });
    }

    [HttpGet("unread-count")]
    public async Task<IActionResult> GetUnreadCount()
    {
        var userIdStr = User.FindFirst("Id")?.Value;
        if (string.IsNullOrEmpty(userIdStr) || !int.TryParse(userIdStr, out int userId))
            return Unauthorized();

        var count = await _noteRepo.GetUnreadCountAsync(userId, false);
        return Ok(count);
    }

    [HttpPut("{noteId}/mark-read")]
    public async Task<IActionResult> MarkAsRead(int noteId)
    {
        await _noteRepo.MarkAsReadAsync(noteId);
        return Ok();
    }
}

public class ReplyDto
{
    public required string Message { get; set; }
}
