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

namespace Meezi.Admin.API.Controllers;

[Route("api/admin/notifications")]
public class AdminNotificationsController : AdminApiControllerBase
{
    private readonly IAdminNotificationService _notifications;

    public AdminNotificationsController(IAdminNotificationService notifications)
    {
        _notifications = notifications;
    }

    [HttpGet]
    public async Task<IActionResult> List(
        [FromQuery] int limit = 50,
        [FromQuery] string? cafeId = null,
        CancellationToken cancellationToken = default)
    {
        var items = await _notifications.ListAsync(limit, cafeId, cancellationToken);
        return Ok(new ApiResponse<object>(true, new { items, total = items.Count }));
    }

    [HttpPost("broadcast")]
    public async Task<IActionResult> Broadcast(
        [FromBody] BroadcastNotificationRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(request.Title))
            return BadRequest(new ApiResponse<object>(false, null, new ApiError("VALIDATION", "Title is required.")));

        var adminId = RequireAdminId(tenant);
        var result = await _notifications.BroadcastAsync(
            request.Title,
            request.Body ?? string.Empty,
            adminId,
            cancellationToken);

        return Ok(new ApiResponse<BroadcastNotificationResult>(true, result));
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(string id, CancellationToken cancellationToken)
    {
        var ok = await _notifications.DeleteAsync(id, cancellationToken);
        if (!ok)
            return NotFound(new ApiResponse<object>(false, null, new ApiError("NOT_FOUND", "Notification not found.")));

        return Ok(new ApiResponse<object>(true, new { id }));
    }
}
