using Microsoft.AspNetCore.Components.Forms; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Json; using System.Text; using System.Threading.Tasks; using TIAMWebApp.Shared.Application.Models; namespace TIAMWebApp.Shared.Application.Services { public class BlogService { private readonly HttpClient _http; public BlogService(HttpClient http) { _http = http; } public async Task> GetAllPostsAsync() { return await _http.GetFromJsonAsync>("/api/blog") ?? new(); } public async Task GetPostByIdAsync(string id) { return await _http.GetFromJsonAsync($"/api/blog/{id}"); } public async Task CreatePostAsync(BlogPostMetadata metadata, IBrowserFile? coverImage) { using var content = new MultipartFormDataContent(); content.Add(new StringContent(metadata.Title ?? ""), "Title"); content.Add(new StringContent(metadata.Lead ?? ""), "Lead"); content.Add(new StringContent(metadata.DriveLink ?? ""), "DriveLink"); content.Add(new StringContent(string.Join(",", metadata.Tags ?? new())), "Tags"); if (coverImage != null) { var fileContent = new StreamContent(coverImage.OpenReadStream(long.MaxValue)); fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(coverImage.ContentType); content.Add(fileContent, "CoverImage", coverImage.Name); } var response = await _http.PostAsync("/api/blog", content); response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync(); } public async Task UpdatePostAsync(BlogPostMetadata metadata, IBrowserFile? newImageFile = null) { using var content = new MultipartFormDataContent(); content.Add(new StringContent(metadata.Title ?? ""), "Title"); content.Add(new StringContent(metadata.Lead ?? ""), "Lead"); content.Add(new StringContent(metadata.DriveLink ?? ""), "DriveLink"); content.Add(new StringContent(string.Join(",", metadata.Tags ?? new List())), "Tags"); if (newImageFile != null) { var stream = newImageFile.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024); // 10 MB max var fileContent = new StreamContent(stream); fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(newImageFile.ContentType); content.Add(fileContent, "CoverImage", newImageFile.Name); } var response = await _http.PutAsync($"/api/blog/{metadata.Id}", content); response.EnsureSuccessStatusCode(); } public async Task DeletePostAsync(string id) { var response = await _http.DeleteAsync($"/api/blog/{id}"); response.EnsureSuccessStatusCode(); } } }