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}/roles")]
public sealed class AdminRolesController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 获取平台角色列表。
    /// </summary>
    /// <param name="keyword">关键字（角色名称/编码）。</param>
    /// <param name="page">页码（从 1 开始）。</param>
    /// <param name="pageSize">每页条数。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>角色分页列表。</returns>
    [HttpGet]
    [PermissionAuthorize("identity:role:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<RoleDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<RoleDto>>> List(
        [FromQuery] string? keyword,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        CancellationToken cancellationToken = default)
    {
        // 1. 构造查询
        var query = new ListAdminRolesQuery
        {
            Keyword = keyword,
            Page = page,
            PageSize = pageSize
        };

        // 2. 执行查询
        var result = await mediator.Send(query, cancellationToken);

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

    /// <summary>
    /// 创建平台角色。
    /// </summary>
    /// <param name="command">创建命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>创建后的角色。</returns>
    [HttpPost]
    [PermissionAuthorize("identity:role:create")]
    [ProducesResponseType(typeof(ApiResponse<RoleDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<RoleDto>> Create(
        [FromBody, Required] CreateAdminRoleCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 执行创建
        var result = await mediator.Send(command, cancellationToken);

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

    /// <summary>
    /// 更新平台角色。
    /// </summary>
    /// <param name="roleId">角色 ID。</param>
    /// <param name="command">更新命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>更新后的角色。</returns>
    [HttpPut("{roleId:long}")]
    [PermissionAuthorize("identity:role:update")]
    [ProducesResponseType(typeof(ApiResponse<RoleDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<RoleDto>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<RoleDto>> Update(
        long roleId,
        [FromBody, Required] UpdateAdminRoleCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 绑定路由参数
        command = command with { RoleId = roleId };

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

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

    /// <summary>
    /// 获取平台角色权限列表。
    /// </summary>
    /// <param name="roleId">角色 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>权限集合。</returns>
    [HttpGet("{roleId:long}/permissions")]
    [PermissionAuthorize("identity:role:read")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<PermissionDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<IReadOnlyList<PermissionDto>>> GetPermissions(
        long roleId,
        CancellationToken cancellationToken)
    {
        // 1. 构造查询
        var query = new GetAdminRolePermissionsQuery { RoleId = roleId };

        // 2. 执行查询
        var result = await mediator.Send(query, cancellationToken);

        // 3. 返回权限集合
        return ApiResponse<IReadOnlyList<PermissionDto>>.Ok(result);
    }

    /// <summary>
    /// 更新平台角色权限。
    /// </summary>
    /// <param name="roleId">角色 ID。</param>
    /// <param name="command">更新命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>更新结果。</returns>
    [HttpPut("{roleId:long}/permissions")]
    [PermissionAuthorize("identity:role:bind-permission")]
    [ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<bool>> UpdatePermissions(
        long roleId,
        [FromBody, Required] UpdateAdminRolePermissionsCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 绑定路由参数
        command = command with { RoleId = roleId };

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

        // 3. 返回更新结果
        return ApiResponse<bool>.Ok(result);
    }

    /// <summary>
    /// 删除平台角色。
    /// </summary>
    /// <param name="roleId">角色 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>删除结果。</returns>
    [HttpDelete("{roleId:long}")]
    [PermissionAuthorize("identity:role:delete")]
    [ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<bool>> Delete(
        long roleId,
        CancellationToken cancellationToken)
    {
        // 1. 构造命令
        var command = new DeleteAdminRoleCommand { RoleId = roleId };

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

        // 3. 返回删除结果
        return ApiResponse<bool>.Ok(result);
    }

    /// <summary>
    /// 克隆平台角色。
    /// </summary>
    /// <param name="roleId">源角色 ID。</param>
    /// <param name="command">克隆命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>克隆后的新角色。</returns>
    [HttpPost("{roleId:long}/clone")]
    [PermissionAuthorize("identity:role:create")]
    [ProducesResponseType(typeof(ApiResponse<RoleDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<RoleDto>> Clone(
        long roleId,
        [FromBody, Required] CloneAdminRoleCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 绑定路由参数
        command = command with { SourceRoleId = roleId };

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

        // 3. 返回克隆结果
        return ApiResponse<RoleDto>.Ok(result);
    }
}
