using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Tiku.Api.Contracts;
using Tiku.Application.Backoffice;
using Tiku.Application.Security;

namespace Tiku.Api.Controllers;

[ApiController]
[Route("api/backoffice")]
public sealed class BackofficeController(
    IBackofficeService backofficeService,
    ICurrentAccessContext currentAccessContext) : ControllerBase
{
    [HttpGet("tenant/ui-bootstrap")]
    [Authorize(Policy = TikuPolicies.TenantBackofficeBootstrap)]
    [EndpointSummary("查询租户后台菜单与权限")]
    [EndpointDescription("返回当前租户管理员可见的后台菜单、权限和模块启用状态。")]
    [ProducesResponseType<BackofficeUiBootstrap>(StatusCodes.Status200OK)]
    public async Task<ActionResult<BackofficeUiBootstrap>> GetTenantUiBootstrap(CancellationToken cancellationToken)
    {
        return Ok(await backofficeService.GetTenantUiBootstrapAsync(
            await currentAccessContext.GetAsync(cancellationToken),
            cancellationToken));
    }

    [HttpGet("tenant/bootstrap")]
    [Authorize(Policy = BackendPermissions.TenantRoleManage)]
    [EndpointSummary("查询租户角色管理初始化数据")]
    [ProducesResponseType<BackofficeBootstrap>(StatusCodes.Status200OK)]
    public async Task<ActionResult<BackofficeBootstrap>> GetTenantBootstrap(CancellationToken cancellationToken)
    {
        return Ok(await backofficeService.GetTenantBootstrapAsync(await ResolveTenantActorAsync(cancellationToken), cancellationToken));
    }

    [HttpGet("platform/ui-bootstrap")]
    [Authorize(Policy = TikuPolicies.PlatformBackofficeBootstrap)]
    [EndpointSummary("查询平台后台菜单与权限")]
    [EndpointDescription("返回当前平台管理员可见的后台菜单、权限和模块启用状态。")]
    [ProducesResponseType<BackofficeUiBootstrap>(StatusCodes.Status200OK)]
    public async Task<ActionResult<BackofficeUiBootstrap>> GetPlatformUiBootstrap(CancellationToken cancellationToken)
    {
        return Ok(await backofficeService.GetPlatformUiBootstrapAsync(
            await currentAccessContext.GetAsync(cancellationToken),
            cancellationToken));
    }

    [HttpPost("tenant/roles")]
    [Authorize(Policy = BackendPermissions.TenantRoleManage)]
    [EndpointSummary("创建或更新租户后台角色")]
    [ProducesResponseType<BackofficeRoleItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<BackofficeRoleItem>> UpsertTenantRole(
        UpsertBackofficeRoleDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await backofficeService.UpsertTenantRoleAsync(await ResolveTenantActorAsync(cancellationToken), request.ToCommand(), cancellationToken));
    }

    [HttpPut("tenant/roles/{roleId:guid}/bindings")]
    [Authorize(Policy = BackendPermissions.TenantRoleManage)]
    [EndpointSummary("替换租户后台角色权限绑定")]
    [ProducesResponseType<BackofficeRoleItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<BackofficeRoleItem>> ReplaceTenantRoleBindings(
        Guid roleId,
        ReplaceRoleBindingsDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await backofficeService.ReplaceTenantRoleBindingsAsync(await ResolveTenantActorAsync(cancellationToken), request.ToCommand(roleId), cancellationToken));
    }

    [HttpPut("tenant/users/{userId:guid}/roles")]
    [Authorize(Policy = BackendPermissions.TenantRoleManage)]
    [EndpointSummary("替换租户用户后台角色")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task<IActionResult> ReplaceTenantUserRoles(
        Guid userId,
        ReplaceUserRolesDto request,
        CancellationToken cancellationToken)
    {
        await backofficeService.ReplaceTenantUserRolesAsync(await ResolveTenantActorAsync(cancellationToken), request.ToCommand(userId), cancellationToken);
        return NoContent();
    }

    [HttpGet("platform/bootstrap")]
    [Authorize(Policy = BackendPermissions.PlatformRoleManage)]
    [EndpointSummary("查询平台角色管理初始化数据")]
    [ProducesResponseType<BackofficeBootstrap>(StatusCodes.Status200OK)]
    public async Task<ActionResult<BackofficeBootstrap>> GetPlatformBootstrap(CancellationToken cancellationToken)
    {
        return Ok(await backofficeService.GetPlatformBootstrapAsync(await ResolvePlatformActorAsync(cancellationToken), cancellationToken));
    }

    [HttpPost("platform/roles")]
    [Authorize(Policy = BackendPermissions.PlatformRoleManage)]
    [EndpointSummary("创建或更新平台后台角色")]
    [ProducesResponseType<BackofficeRoleItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<BackofficeRoleItem>> UpsertPlatformRole(
        UpsertBackofficeRoleDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await backofficeService.UpsertPlatformRoleAsync(await ResolvePlatformActorAsync(cancellationToken), request.ToCommand(), cancellationToken));
    }

    [HttpPut("platform/roles/{roleId:guid}/bindings")]
    [Authorize(Policy = BackendPermissions.PlatformRoleManage)]
    [EndpointSummary("替换平台后台角色权限绑定")]
    [ProducesResponseType<BackofficeRoleItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<BackofficeRoleItem>> ReplacePlatformRoleBindings(
        Guid roleId,
        ReplaceRoleBindingsDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await backofficeService.ReplacePlatformRoleBindingsAsync(await ResolvePlatformActorAsync(cancellationToken), request.ToCommand(roleId), cancellationToken));
    }

    [HttpPut("platform/users/{userId:guid}/roles")]
    [Authorize(Policy = BackendPermissions.PlatformRoleManage)]
    [EndpointSummary("替换平台用户后台角色")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task<IActionResult> ReplacePlatformUserRoles(
        Guid userId,
        ReplaceUserRolesDto request,
        CancellationToken cancellationToken)
    {
        await backofficeService.ReplacePlatformUserRolesAsync(await ResolvePlatformActorAsync(cancellationToken), request.ToCommand(userId), cancellationToken);
        return NoContent();
    }

    private async Task<BackofficeActor> ResolveTenantActorAsync(CancellationToken cancellationToken)
    {
        return BackofficeActor.FromTenantAccess(await currentAccessContext.GetAsync(cancellationToken));
    }

    private async Task<BackofficeActor> ResolvePlatformActorAsync(CancellationToken cancellationToken)
    {
        return BackofficeActor.FromPlatformAccess(await currentAccessContext.GetAsync(cancellationToken));
    }
}
