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

namespace SIGCM.API.Controllers;

[ApiController]
[Route("api/listings/{listingId}/[controller]")]
[Authorize(Roles = "Admin,Moderador")]
public class NotesController : ControllerBase
{
    private readonly IListingNoteRepository _noteRepo;

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

    [HttpPost]
    public async Task<IActionResult> CreateNote(int listingId, [FromBody] CreateNoteDto dto)
    {
        var userIdStr = User.FindFirst("Id")?.Value;
        if (string.IsNullOrEmpty(userIdStr) || !int.TryParse(userIdStr, out int moderatorId))
            return Unauthorized();

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

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

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

[ApiController]
[Route("api/[controller]")]
[Authorize(Roles = "Admin,Moderador")]
public class ModerationStatsController : ControllerBase
{
    private readonly IListingNoteRepository _noteRepo;

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

    [HttpGet("unread-count")]
    public async Task<IActionResult> GetUnreadCount()
    {
        var count = await _noteRepo.GetUnreadCountAsync(0, true);
        return Ok(count);
    }
}

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