using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using TakeoutSaaS.Application.App.StoreAudits.Commands;
using TakeoutSaaS.Application.App.StoreAudits.Dto;
using TakeoutSaaS.Application.App.StoreAudits.Queries;
using TakeoutSaaS.Module.Authorization.Attributes;
using TakeoutSaaS.Shared.Abstractions.Constants;
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}/platform/store-audits")]
public sealed class StoreAuditsController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 查询待审核门店列表。
    /// </summary>
    /// <returns>待审核门店分页列表。</returns>
    [HttpGet("pending")]
    [PermissionAuthorize("store-audit:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<PendingStoreAuditDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<PendingStoreAuditDto>>> ListPending(
        [FromQuery] ListPendingStoreAuditsQuery query,
        CancellationToken cancellationToken)
    {
        // 1. 查询待审核门店列表
        var result = await mediator.Send(query, cancellationToken);

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

    /// <summary>
    /// 获取门店审核详情。
    /// </summary>
    /// <param name="storeId">门店 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>审核详情。</returns>
    [HttpGet("{storeId:long}")]
    [PermissionAuthorize("store-audit:read")]
    [ProducesResponseType(typeof(ApiResponse<StoreAuditDetailDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<StoreAuditDetailDto>> GetDetail(long storeId, CancellationToken cancellationToken)
    {
        // 1. 获取审核详情
        var result = await mediator.Send(new GetStoreAuditDetailQuery { StoreId = storeId }, cancellationToken);

        // 2. 返回详情或未找到
        return result is null
            ? ApiResponse<StoreAuditDetailDto>.Error(ErrorCodes.NotFound, "门店不存在")
            : ApiResponse<StoreAuditDetailDto>.Ok(result);
    }

    /// <summary>
    /// 审核通过。
    /// </summary>
    /// <param name="storeId">门店 ID。</param>
    /// <param name="command">审核命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>操作结果。</returns>
    [HttpPost("{storeId:long}/approve")]
    [PermissionAuthorize("store-audit:approve")]
    [ProducesResponseType(typeof(ApiResponse<StoreAuditActionResultDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<StoreAuditActionResultDto>> Approve(
        long storeId,
        [FromBody, Required] ApproveStoreCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 执行审核通过
        var request = command with { StoreId = storeId };
        var result = await mediator.Send(request, cancellationToken);

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

    /// <summary>
    /// 审核驳回。
    /// </summary>
    /// <param name="storeId">门店 ID。</param>
    /// <param name="command">驳回命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>操作结果。</returns>
    [HttpPost("{storeId:long}/reject")]
    [PermissionAuthorize("store-audit:reject")]
    [ProducesResponseType(typeof(ApiResponse<StoreAuditActionResultDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<StoreAuditActionResultDto>> Reject(
        long storeId,
        [FromBody, Required] RejectStoreCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 执行审核驳回
        var request = command with { StoreId = storeId };
        var result = await mediator.Send(request, cancellationToken);

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

    /// <summary>
    /// 查询审核记录。
    /// </summary>
    /// <param name="storeId">门店 ID。</param>
    /// <param name="page">页码。</param>
    /// <param name="pageSize">每页数量。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>审核记录分页列表。</returns>
    [HttpGet("{storeId:long}/records")]
    [PermissionAuthorize("store-audit:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<StoreAuditRecordDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<StoreAuditRecordDto>>> ListRecords(
        long storeId,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        CancellationToken cancellationToken = default)
    {
        // 1. 执行记录查询
        var query = new ListStoreAuditRecordsQuery
        {
            StoreId = storeId,
            Page = page,
            PageSize = pageSize
        };
        var result = await mediator.Send(query, cancellationToken);

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

    /// <summary>
    /// 获取审核统计数据。
    /// </summary>
    /// <param name="query">查询参数。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>统计数据。</returns>
    [HttpGet("statistics")]
    [PermissionAuthorize("store-audit:read")]
    [ProducesResponseType(typeof(ApiResponse<StoreAuditStatisticsDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<StoreAuditStatisticsDto>> GetStatistics(
        [FromQuery] GetStoreAuditStatisticsQuery query,
        CancellationToken cancellationToken)
    {
        // 1. 执行统计查询
        var result = await mediator.Send(query, cancellationToken);

        // 2. 返回统计结果
        return ApiResponse<StoreAuditStatisticsDto>.Ok(result);
    }

    /// <summary>
    /// 强制关闭门店。
    /// </summary>
    /// <param name="storeId">门店 ID。</param>
    /// <param name="command">关闭命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>操作结果。</returns>
    [HttpPost("{storeId:long}/force-close")]
    [PermissionAuthorize("store-audit:force-close")]
    [ProducesResponseType(typeof(ApiResponse<StoreAuditActionResultDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<StoreAuditActionResultDto>> ForceClose(
        long storeId,
        [FromBody, Required] ForceCloseStoreCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 执行强制关闭
        var request = command with { StoreId = storeId };
        var result = await mediator.Send(request, cancellationToken);

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

    /// <summary>
    /// 解除强制关闭。
    /// </summary>
    /// <param name="storeId">门店 ID。</param>
    /// <param name="command">解除命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>操作结果。</returns>
    [HttpPost("{storeId:long}/reopen")]
    [PermissionAuthorize("store-audit:force-close")]
    [ProducesResponseType(typeof(ApiResponse<StoreAuditActionResultDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<StoreAuditActionResultDto>> Reopen(
        long storeId,
        [FromBody, Required] ReopenStoreCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 执行解除强制关闭
        var request = command with { StoreId = storeId };
        var result = await mediator.Send(request, cancellationToken);

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