using FastEndpoints; using FrameworkBLL.DataSync; using GB5Shared.DTO.Framework.Login; using GB5Shared.DTO.Framework.ResponseStandard; using GB5Shared.FastEndPoint; using Microsoft.AspNetCore.Http; using static GB5Shared.GB5Constant.Constant; namespace FrameworkSL.Endpoints.DataSync { public class ImportFromFile : EndpointWithoutRequest> { private readonly IDataSyncImportBLL _bll; public ImportFromFile(IDataSyncImportBLL bll) => _bll = bll; public override void Configure() { Post("/DataSync/ImportFromFile"); AllowAnonymous(); AllowFileUploads(); } public override async Task> ExecuteAsync(CancellationToken ct) { var loginHeader = HttpContext.Request.Headers["Login"].FirstOrDefault() ?? throw new InvalidOperationException("Login header is missing."); var login = System.Text.Json.JsonSerializer.Deserialize(loginHeader) ?? throw new InvalidOperationException("Login header contains invalid JSON."); var file = HttpContext.Request.Form.Files.FirstOrDefault() ?? throw new InvalidOperationException("No file uploaded."); if (!int.TryParse(HttpContext.Request.Form["TargetDBInstanceId"], out var targetDbInstanceId) || targetDbInstanceId <= 0) throw new InvalidOperationException("TargetDBInstanceId is required and must be a positive integer."); byte.TryParse(HttpContext.Request.Form["ConflictPolicy"], out var conflictPolicy); try { await using var stream = file.OpenReadStream(); var runId = await _bll.ImportFromFileAsync(stream, targetDbInstanceId, conflictPolicy, login, ct).ConfigureAwait(false); return await GB5Shared.ResponseStandard.Response.CreateSuccessResponse( runId.ToString(), CacheKeyLevel.NOT_REQUIRED, login); } catch (Exception ex) { return await GB5Shared.ResponseStandard.Response.CreateExceptionError( ex, CacheKeyLevel.NOT_REQUIRED, login, ex.Message, 500); } } } }