using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
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}/announcements")]
public sealed class TenantAnnouncementsController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 分页查询公告。
    /// </summary>
    /// <returns>租户公告分页结果。</returns>
    [HttpGet]
    [PermissionAuthorize("tenant-announcement:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<TenantAnnouncementDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<TenantAnnouncementDto>>> Search(long tenantId, [FromQuery] SearchTenantAnnouncementsQuery query, CancellationToken cancellationToken)
    {
        // 1. 绑定租户标识
        query = query with { TenantId = tenantId };

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

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

    /// <summary>
    /// 公告详情。
    /// </summary>
    /// <returns>租户公告详情。</returns>
    [HttpGet("{announcementId:long}")]
    [PermissionAuthorize("tenant-announcement:read")]
    [ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<TenantAnnouncementDto>> Detail(long tenantId, long announcementId, CancellationToken cancellationToken)
    {
        // 1. 查询指定公告
        var result = await mediator.Send(new GetTenantAnnouncementQuery { TenantId = tenantId, AnnouncementId = announcementId }, cancellationToken);

        // 2. 返回详情或 404
        return result is null
            ? ApiResponse<TenantAnnouncementDto>.Error(StatusCodes.Status404NotFound, "公告不存在")
            : ApiResponse<TenantAnnouncementDto>.Ok(result);
    }

    /// <summary>
    /// 创建公告。
    /// </summary>
    /// <returns>创建的公告信息。</returns>
    [HttpPost]
    [PermissionAuthorize("tenant-announcement:create")]
    [ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<TenantAnnouncementDto>> Create(long tenantId, [FromBody, Required] CreateTenantAnnouncementCommand command, CancellationToken cancellationToken)
    {
        // 1. 绑定租户标识
        command = command with { TenantId = tenantId };

        // 2. 创建公告并返回
        var result = await mediator.Send(command, cancellationToken);
        return ApiResponse<TenantAnnouncementDto>.Ok(result);
    }

    /// <summary>
    /// 更新公告。
    /// </summary>
    /// <returns>更新后的公告信息。</returns>
    [HttpPut("{announcementId:long}")]
    [PermissionAuthorize("tenant-announcement:update")]
    [ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<TenantAnnouncementDto>> Update(long tenantId, long announcementId, [FromBody, Required] UpdateTenantAnnouncementCommand command, CancellationToken cancellationToken)
    {
        // 1. 绑定租户与公告标识
        command = command with { TenantId = tenantId, AnnouncementId = announcementId };

        // 2. 执行更新
        var result = await mediator.Send(command, cancellationToken);

        // 3. 返回更新结果或 404
        return result is null
            ? ApiResponse<TenantAnnouncementDto>.Error(StatusCodes.Status404NotFound, "公告不存在")
            : ApiResponse<TenantAnnouncementDto>.Ok(result);
    }

    /// <summary>
    /// 删除公告。
    /// </summary>
    /// <returns>删除结果。</returns>
    [HttpDelete("{announcementId:long}")]
    [PermissionAuthorize("tenant-announcement:delete")]
    [ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<bool>> Delete(long tenantId, long announcementId, CancellationToken cancellationToken)
    {
        // 1. 删除公告
        var result = await mediator.Send(new DeleteTenantAnnouncementCommand { TenantId = tenantId, AnnouncementId = announcementId }, cancellationToken);

        // 2. 返回执行结果
        return ApiResponse<bool>.Ok(result);
    }

    /// <summary>
    /// 标记公告已读。
    /// </summary>
    /// <returns>标记已读后的公告信息。</returns>
    [HttpPost("{announcementId:long}/read")]
    [PermissionAuthorize("tenant-announcement:read")]
    [ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<TenantAnnouncementDto>> MarkRead(long tenantId, long announcementId, CancellationToken cancellationToken)
    {
        // 1. 标记公告已读
        var result = await mediator.Send(new MarkTenantAnnouncementReadCommand { TenantId = tenantId, AnnouncementId = announcementId }, cancellationToken);

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