using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Application.Identity.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}/menus")]
public sealed class MenusController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 获取当前租户的菜单列表（平铺）。
    /// </summary>
    [HttpGet]
    [PermissionAuthorize("identity:menu:read")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<MenuDefinitionDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<IReadOnlyList<MenuDefinitionDto>>> List(CancellationToken cancellationToken)
    {
        // 1. 查询菜单列表
        var result = await mediator.Send(new ListMenusQuery(), cancellationToken);

        // 2. 返回数据
        return ApiResponse<IReadOnlyList<MenuDefinitionDto>>.Ok(result);
    }

    /// <summary>
    /// 获取菜单详情。
    /// </summary>
    [HttpGet("{menuId:long}")]
    [PermissionAuthorize("identity:menu:read")]
    [ProducesResponseType(typeof(ApiResponse<MenuDefinitionDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<MenuDefinitionDto>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<MenuDefinitionDto>> Detail(long menuId, CancellationToken cancellationToken)
    {
        // 1. 查询详情
        var result = await mediator.Send(new MenuDetailQuery { Id = menuId }, cancellationToken);

        // 2. 返回或 404
        return result is null
            ? ApiResponse<MenuDefinitionDto>.Error(StatusCodes.Status404NotFound, "菜单不存在")
            : ApiResponse<MenuDefinitionDto>.Ok(result);
    }

    /// <summary>
    /// 创建菜单。
    /// </summary>
    [HttpPost]
    [PermissionAuthorize("identity:menu:create")]
    [ProducesResponseType(typeof(ApiResponse<MenuDefinitionDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<MenuDefinitionDto>> Create([FromBody, Required] CreateMenuCommand command, CancellationToken cancellationToken)
    {
        // 1. 创建菜单
        var result = await mediator.Send(command, cancellationToken);

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

    /// <summary>
    /// 更新菜单。
    /// </summary>
    [HttpPut("{menuId:long}")]
    [PermissionAuthorize("identity:menu:update")]
    [ProducesResponseType(typeof(ApiResponse<MenuDefinitionDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<MenuDefinitionDto>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<MenuDefinitionDto>> Update(
        long menuId,
        [FromBody, Required] UpdateMenuCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 绑定菜单 ID
        command = command with { Id = menuId };

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

        // 3. 返回或 404
        return result is null
            ? ApiResponse<MenuDefinitionDto>.Error(StatusCodes.Status404NotFound, "菜单不存在")
            : ApiResponse<MenuDefinitionDto>.Ok(result);
    }

    /// <summary>
    /// 删除菜单。
    /// </summary>
    [HttpDelete("{menuId:long}")]
    [PermissionAuthorize("identity:menu:delete")]
    [ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<bool>> Delete(long menuId, CancellationToken cancellationToken)
    {
        // 1. 删除菜单
        var result = await mediator.Send(new DeleteMenuCommand { Id = menuId }, cancellationToken);

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