using Microsoft.AspNetCore.Mvc;
using Meezi.API.Models.Notifications;
using Meezi.API.Services;
using Meezi.Core.Interfaces;
using Meezi.Shared;

namespace Meezi.API.Controllers;

[Route("api/cafes/{cafeId}/notifications")]
public class NotificationsController : CafeApiControllerBase
{
    private readonly INotificationInboxService _inbox;

    public NotificationsController(INotificationInboxService inbox)
    {
        _inbox = inbox;
    }

    [HttpGet]
    public async Task<IActionResult> List(
        string cafeId,
        ITenantContext tenant,
        [FromQuery] bool unreadOnly = false,
        [FromQuery] int limit = 40,
        CancellationToken ct = default)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _inbox.ListAsync(cafeId, unreadOnly, limit, ct);
        return Ok(new ApiResponse<NotificationListDto>(true, data));
    }

    [HttpGet("unread-count")]
    public async Task<IActionResult> UnreadCount(string cafeId, ITenantContext tenant, CancellationToken ct = default)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var count = await _inbox.GetUnreadCountAsync(cafeId, ct);
        return Ok(new ApiResponse<object>(true, new { count }));
    }

    [HttpPost("read")]
    public async Task<IActionResult> MarkRead(
        string cafeId,
        [FromBody] MarkNotificationsReadRequest request,
        ITenantContext tenant,
        CancellationToken ct = default)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        await _inbox.MarkReadAsync(cafeId, request, ct);
        return Ok(new ApiResponse<object>(true, new { read = true }));
    }
}
