using back.context; using back.DataModels; using back.DTO; using back.persistance.blob; using Microsoft.AspNetCore.Mvc; namespace back.controllers; [Route("api/[controller]")] [ApiController] public class PhotosController(PhotoContext photoContext, IBlobStorageService blobStorage) : ControllerBase { private readonly PhotoContext _photoContext = photoContext; // GET: api/ [HttpGet] public async Task>> Get([FromQuery] int page = 1, [FromQuery] int pageSize = 20) { var photos = await _photoContext.GetPage(page, pageSize); var totalItems = await _photoContext.GetTotalItems(); Response.Headers.Append("X-Total-Count", totalItems.ToString()); return Ok(photos); } // GET api//5 [HttpGet("{res}/{id}")] public async Task Get(string res, Guid id) { var photo = await _photoContext.GetById(id); if (photo == null) return NotFound(); string? filePath = res.ToLower() switch { "high" => photo.HighResUrl, "mid" => photo.MidResUrl, "low" or _ => photo.LowResUrl }; string? mediaType = res.ToLower() switch { "high" => $"image/{photo.Extension}", "mid" or "low" or _ => "image/webp", }; if (filePath == null) { return NotFound(); } var file = await blobStorage.GetBytesAsync(filePath); if (file == null) { return NotFound(); } return File(file, mediaType); } // POST api/ [HttpPost] public async Task Post([FromForm] PhotoFormModel form) { try { if (form.Image == null || form.Image.Length == 0) return BadRequest("No image uploaded."); await _photoContext.CreateNew(form); return Created(); } catch { return BadRequest(); } } //// PUT api/ [HttpPut] public async Task Put([FromBody] PhotoModel photo) { await _photoContext.Update(photo); return NoContent(); } // DELETE api//5 [HttpDelete("{id}")] public async Task Delete(Guid id) { var photo = await _photoContext.GetById(id); if (photo == null) return NotFound(); await _photoContext.Delete(photo); return NoContent(); } }