using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.SystemParameters.Commands;
using TakeoutSaaS.Application.App.SystemParameters.Dto;
using TakeoutSaaS.Application.App.SystemParameters.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>
/// <remarks>
/// 提供参数的新增、修改、查询与删除。
/// </remarks>
[ApiVersion("1.0")]
[Authorize]
[Route("api/admin/v{version:apiVersion}/system-parameters")]
public sealed class SystemParametersController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 创建系统参数。
    /// </summary>
    /// <returns>创建的系统参数信息。</returns>
    [HttpPost]
    [PermissionAuthorize("system-parameter:create")]
    [ProducesResponseType(typeof(ApiResponse<SystemParameterDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<SystemParameterDto>> Create([FromBody] CreateSystemParameterCommand command, CancellationToken cancellationToken)
    {
        // 1. 创建系统参数
        var result = await mediator.Send(command, cancellationToken);

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

    /// <summary>
    /// 查询系统参数列表。
    /// </summary>
    /// <returns>分页的系统参数列表。</returns>
    [HttpGet]
    [PermissionAuthorize("system-parameter:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<SystemParameterDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<SystemParameterDto>>> List(
        [FromQuery] string? keyword,
        [FromQuery] bool? isEnabled,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        [FromQuery] string? sortBy = null,
        [FromQuery] bool sortDesc = true,
        CancellationToken cancellationToken = default)
    {
        // 1. 组合查询参数
        var result = await mediator.Send(new SearchSystemParametersQuery
        {
            Keyword = keyword,
            IsEnabled = isEnabled,
            Page = page,
            PageSize = pageSize,
            SortBy = sortBy,
            SortDescending = sortDesc
        }, cancellationToken);

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

    /// <summary>
    /// 获取系统参数详情。
    /// </summary>
    /// <returns>系统参数详情。</returns>
    [HttpGet("{parameterId:long}")]
    [PermissionAuthorize("system-parameter:read")]
    [ProducesResponseType(typeof(ApiResponse<SystemParameterDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<SystemParameterDto>> Detail(long parameterId, CancellationToken cancellationToken)
    {
        // 1. 查询参数详情
        var result = await mediator.Send(new GetSystemParameterByIdQuery(parameterId), cancellationToken);

        // 2. 返回详情或 404
        return result == null
            ? ApiResponse<SystemParameterDto>.Error(ErrorCodes.NotFound, "系统参数不存在")
            : ApiResponse<SystemParameterDto>.Ok(result);
    }

    /// <summary>
    /// 更新系统参数。
    /// </summary>
    /// <returns>更新后的系统参数信息。</returns>
    [HttpPut("{parameterId:long}")]
    [PermissionAuthorize("system-parameter:update")]
    [ProducesResponseType(typeof(ApiResponse<SystemParameterDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<SystemParameterDto>> Update(long parameterId, [FromBody] UpdateSystemParameterCommand command, CancellationToken cancellationToken)
    {
        // 1. 确保命令包含参数标识
        if (command.ParameterId == 0)
        {
            command = command with { ParameterId = parameterId };
        }

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

        // 3. 返回结果或 404
        return result == null
            ? ApiResponse<SystemParameterDto>.Error(ErrorCodes.NotFound, "系统参数不存在")
            : ApiResponse<SystemParameterDto>.Ok(result);
    }

    /// <summary>
    /// 删除系统参数。
    /// </summary>
    /// <returns>删除结果。</returns>
    [HttpDelete("{parameterId:long}")]
    [PermissionAuthorize("system-parameter:delete")]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<object>> Delete(long parameterId, CancellationToken cancellationToken)
    {
        // 1. 执行删除
        var success = await mediator.Send(new DeleteSystemParameterCommand { ParameterId = parameterId }, cancellationToken);

        // 2. 返回成功或 404
        return success
            ? ApiResponse.Success()
            : ApiResponse<object>.Error(ErrorCodes.NotFound, "系统参数不存在");
    }
}
