using FastEndpoints; using FrameworkBLL.DataSync; using GB5Shared.DTO.Framework.Login; using GB5Shared.DTO.Framework.ResponseStandard; using GB5Shared.FastEndPoint; using static GB5Shared.GB5Constant.Constant; namespace FrameworkSL.Endpoints.DataSync { // Fires an async sync run and returns the RunId immediately (fire-and-forget). // The caller may subscribe to SignalR hub group "datasync:{runId}" for progress updates. public class TriggerSyncJob : BaseEndpoint> { private readonly IDataSyncRunBLL _runBll; public TriggerSyncJob(IDataSyncRunBLL runBll) => _runBll = runBll; public override void Configure() { Post("/DataSync/TriggerSyncJob"); AllowAnonymous(); } public record TriggerSyncJobParameters( [property: FromHeader] string Login, [property: QueryParam] int SyncJobId ); protected override string? GetCacheKey(TriggerSyncJobParameters req, LoginDTO login) => null; protected override async Task> ExecuteAsync( TriggerSyncJobParameters req, LoginDTO login, CancellationToken ct) { try { // Start the run on a background thread — do not await the full execution. // ExecuteSyncJobAsync creates the TDSYNCRUNLOG row synchronously before returning RunId. var runId = await _runBll.ExecuteSyncJobAsync( req.SyncJobId, triggeredBy: 1, triggeredByUserId: login.UserId, login, ct); return await GB5Shared.ResponseStandard.Response.CreateSuccessResponse( $"Sync job triggered. RunId = {runId}. Subscribe to datasync:{runId} for progress.", CacheKeyLevel.NOT_REQUIRED, login); } catch (Exception ex) { return await GB5Shared.ResponseStandard.Response.CreateExceptionError( ex, CacheKeyLevel.NOT_REQUIRED, login, ex.Message, 500); } } } }