using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.App.Tenants.Queries;
using TakeoutSaaS.Module.Authorization.Attributes;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Web.Api;

namespace TakeoutSaaS.AdminApi.Controllers;

/// <summary>
/// 租户通知接口。
/// </summary>
[ApiVersion("1.0")]
[Authorize]
[Route("api/admin/v{version:apiVersion}/tenants/{tenantId:long}/notifications")]
public sealed class TenantNotificationsController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 分页查询通知。
    /// </summary>
    /// <returns>租户通知分页结果。</returns>
    [HttpGet]
    [PermissionAuthorize("tenant-notification:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<TenantNotificationDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<TenantNotificationDto>>> Search(long tenantId, [FromQuery] SearchTenantNotificationsQuery query, CancellationToken cancellationToken)
    {
        // 1. 绑定租户标识
        query = query with { TenantId = tenantId };

        // 2. 查询通知列表
        var result = await mediator.Send(query, cancellationToken);

        // 3. 返回分页结果
        return ApiResponse<PagedResult<TenantNotificationDto>>.Ok(result);
    }

    /// <summary>
    /// 标记通知已读。
    /// </summary>
    /// <returns>标记已读后的通知信息。</returns>
    [HttpPost("{notificationId:long}/read")]
    [PermissionAuthorize("tenant-notification:update")]
    [ProducesResponseType(typeof(ApiResponse<TenantNotificationDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<TenantNotificationDto>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<TenantNotificationDto>> MarkRead(long tenantId, long notificationId, CancellationToken cancellationToken)
    {
        // 1. 标记通知为已读
        var result = await mediator.Send(new MarkTenantNotificationReadCommand { TenantId = tenantId, NotificationId = notificationId }, cancellationToken);

        // 2. 返回结果或 404
        return result is null
            ? ApiResponse<TenantNotificationDto>.Error(StatusCodes.Status404NotFound, "通知不存在")
            : ApiResponse<TenantNotificationDto>.Ok(result);
    }
}
