using LiteCharms.Features.S3.Abstractions; namespace LiteCharms.Features.S3; public class BookstoreInvoicesS3Service(IConfiguration configuration, [FromKeyedServices(Constants.BookshopInvoicesBucketName)] IAmazonS3 amazonS3) : S3ServiceBase(amazonS3), IS3Service { public override async Task> UploadFileAsync(string fileName, Stream fileStream, string contentType, CancellationToken cancellationToken = default) { try { var bucketName = configuration.GetSection($"{Constants.BookshopInvoicesS3SettingsSection}:BucketName").Value!; var cdnBaseUrl = configuration.GetSection($"{Constants.BookshopInvoicesS3SettingsSection}:CdnBaseUrl").Value!; if(string.IsNullOrWhiteSpace(bucketName)) return Result.Fail("Bucket name is not configured."); if (string.IsNullOrWhiteSpace(cdnBaseUrl)) return Result.Fail("CDN base URL is not configured."); var response = await client.PutObjectAsync(new PutObjectRequest { BucketName = bucketName, Key = fileName, InputStream = fileStream, ContentType = contentType }, cancellationToken); return response.HttpStatusCode != System.Net.HttpStatusCode.OK ? Result.Fail($"Failed to upload {fileName} to S3.") : Result.Ok(string.Format(cdnBaseUrl, bucketName, fileName)); } catch (Exception ex) { return Result.Fail(new Error($"Error uploading {fileName} to S3: {ex.Message}").CausedBy(ex)); } } }