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

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("租户端-前端配置")]
[Authorize(Policy = BackendPermissions.TenantSettingsManage)]
[Produces("application/json")]
[Route("api/tenant/frontend-config")]
public sealed class TenantFrontendConfigController(
    ITenantContext tenantContext,
    ITenantFrontendConfigService frontendConfigService) : ControllerBase
{
    [HttpGet]
    [EndpointSummary("查询租户前端配置")]
    public Task<TenantFrontendConfigItem> Get(CancellationToken cancellationToken)
    {
        return frontendConfigService.GetAsync(RequireTenantId(), cancellationToken);
    }

    [HttpPut("draft")]
    [EndpointSummary("保存租户前端配置草稿")]
    public Task<TenantFrontendConfigItem> SaveDraft(
        SaveTenantFrontendConfigDraftDto request,
        CancellationToken cancellationToken)
    {
        return frontendConfigService.SaveDraftAsync(
            RequireTenantId(),
            request.ToDraft(),
            cancellationToken);
    }

    [HttpPost("publish")]
    [EndpointSummary("发布租户前端配置")]
    public Task<TenantFrontendConfigItem> Publish(
        PublishTenantFrontendConfigDto request,
        CancellationToken cancellationToken)
    {
        return frontendConfigService.PublishAsync(
            RequireTenantId(),
            request.ExpectedVersion,
            cancellationToken);
    }

    private Guid RequireTenantId()
    {
        return tenantContext.TenantId ?? throw new TenantFrontendConfigException(
            "tenant_not_resolved",
            "Tenant was not resolved.");
    }
}