using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Tiku.Api.Contracts;
using Tiku.Application.Auth;
using Tiku.Application.Catalog;
using Tiku.Application.Content;
using Tiku.Application.Security;
using Tiku.Application.TenantAdmin;

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("租户端-运营管理")]
[Produces("application/json")]
[Route("api/tenant")]
public sealed class TenantDomainProviderController(
    ITenantDomainProviderService domainProviderService,
    TenantAdminActorResolver actorResolver) : ControllerBase
{
    [HttpGet("domains")]
    [Authorize(Policy = BackendPermissions.TenantSettingsManage)]
    [EndpointSummary("查询租户域名")]
    [ProducesResponseType<CatalogList<TenantDomainItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CatalogList<TenantDomainItem>>> GetDomains(CancellationToken cancellationToken)
    {
        return Ok(await domainProviderService.GetDomainsAsync(actorResolver.Resolve(), cancellationToken));
    }

    [HttpPost("domains")]
    [Authorize(Policy = BackendPermissions.TenantSettingsManage)]
    [EndpointSummary("添加租户域名")]
    [ProducesResponseType<ContentManagementResult<TenantDomainItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<ContentManagementResult<TenantDomainItem>>> CreateDomain(
        CreateTenantDomainDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await domainProviderService.CreateDomainAsync(actorResolver.Resolve(), request.ToCommand(), cancellationToken));
    }

    [HttpGet("auth-providers")]
    [Authorize(Policy = BackendPermissions.TenantProviderManage)]
    [EndpointSummary("查询租户登录 Provider 公开配置")]
    [ProducesResponseType<CatalogList<TenantIdentityProviderItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CatalogList<TenantIdentityProviderItem>>> GetAuthProviders(
        CancellationToken cancellationToken)
    {
        return Ok(await domainProviderService.GetAuthProvidersAsync(actorResolver.Resolve(), cancellationToken));
    }

    [HttpPut("auth-providers")]
    [Authorize(Policy = BackendPermissions.TenantProviderManage)]
    [EndpointSummary("新增或更新租户登录 Provider")]
    [ProducesResponseType<ContentManagementResult<TenantIdentityProviderItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<ContentManagementResult<TenantIdentityProviderItem>>> UpsertAuthProvider(
        UpsertTenantIdentityProviderDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await domainProviderService.UpsertAuthProviderAsync(actorResolver.Resolve(), request.ToCommand(),
            cancellationToken));
    }
}

