using FastEndpoints;
using Kbx.Shared.ExternalData;
using Kbx.Shared.ExternalData.Generated;
using Kbx.Shared.Runtime;
using Shared.Problems;

namespace Kbx.Modules.Common.ExternalData.Refresh;

public sealed record Response(string DatasetId,string Status);
public sealed class Endpoint(IKbxExternalDataRefreshScheduler scheduler):EndpointWithoutRequest<Response>
{
    public override void Configure(){Post("/api/kbx/external-data/{datasetId}/refresh");Permissions("common.external-data.refresh");}
    public override async Task HandleAsync(CancellationToken ct)
    {
        var datasetId=Route<string>("datasetId")!;
        if(!KbxExternalDataCatalog.All.TryGetValue(datasetId,out var dataset))
        { await Send.ResponseAsync(KbxNotFoundProblem.Create("EXTERNAL_DATASET_NOT_FOUND","외부 데이터셋을 찾을 수 없습니다."),404,cancellation:ct); return; }
        if(dataset.FreshnessMode=="provider-defined" && dataset.FreshForSeconds is null)
        { await Send.ResponseAsync(KbxBusinessProblem.Create("EXTERNAL_DATA_POLICY_REQUIRED","승인된 서비스별 신선도 정책이 먼저 필요합니다.","KRX 범용 데이터셋에는 임의 TTL을 적용하지 않습니다."),422,cancellation:ct); return; }
        await scheduler.ScheduleDatasetAsync(RuntimeIdentity.TenantId(User),datasetId,ct);
        await Send.ResponseAsync(new Response(datasetId,"queued"),202,cancellation:ct);
    }
}
