using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Tiku.Api.Contracts;
using Tiku.Api.OpenApi;
using Tiku.Application.Auth;
using Tiku.Application.PlatformAdmin;
using Tiku.Application.Security;
using Tiku.Domain.Platform;

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("平台端-平台管理")]
[Authorize(Policy = BackendPermissions.PlatformDashboardView)]
[Produces("application/json")]
[Route("api/platform")]
public sealed class PlatformStaffAccessController(
    IPlatformStaffAccessService service,
    IAuthAdministrationService authAdministrationService,
    PlatformAdminActorResolver actorResolver) : ControllerBase
{
    [HttpGet("staff")]
    [Authorize(Policy = BackendPermissions.PlatformStaffManage)]
    [EndpointSummary("查询平台员工列表")]
    [ProducesResponseType<PlatformStaffList>(StatusCodes.Status200OK)]
    public async Task<ActionResult<PlatformStaffList>> Staff(
        [FromQuery] PlatformAdminQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetStaffAsync(actorResolver.Resolve(), query.ToQuery(), cancellationToken));
    }

    [HttpPut("staff")]
    [Authorize(Policy = BackendPermissions.PlatformStaffManage)]
    [EndpointSummary("创建或更新平台员工")]
    [ProducesResponseType<PlatformStaffItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<PlatformStaffItem>> UpsertStaff(
        UpsertPlatformStaffDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.UpsertStaffAsync(actorResolver.Resolve(), request.ToCommand(), cancellationToken));
    }

    [HttpPatch("staff/status")]
    [Authorize(Policy = BackendPermissions.PlatformStaffManage)]
    [EndpointSummary("启用或禁用平台员工")]
    [ProducesResponseType<PlatformStaffItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<PlatformStaffItem>> StaffStatus(
        UpdatePlatformStaffStatusDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.UpdateStaffStatusAsync(actorResolver.Resolve(), request.ToCommand(),
            cancellationToken));
    }

    [HttpPost("staff/{userId:guid}/password-reset")]
    [Authorize(Policy = BackendPermissions.PlatformStaffManage)]
    [EndpointSummary("为平台员工设置一次性临时密码")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task<IActionResult> ResetStaffPassword(
        Guid userId,
        AdministrativePasswordResetDto request,
        CancellationToken cancellationToken)
    {
        var actor = actorResolver.Resolve();
        await authAdministrationService.ResetPasswordAsync(
            new AdministrativePasswordResetRequest(
                actor.UserId,
                userId,
                null,
                request.TemporaryPassword,
                request.Reason),
            cancellationToken);
        return NoContent();
    }
}
