using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Diagnostics.HealthChecks; using System.Text.Json; namespace ContactsApp { [ApiController] [Route("api/contacts")] public class ContactController(IContactRepository repository) : ControllerBase { [HttpGet] public ActionResult> GetAll() { var contacts = repository.GetAll().ToList(); return Ok(contacts); } [HttpPost] public ActionResult Create([FromBody] Contact contact) { repository.AddContact(contact); return Ok(contact); } [HttpGet("{id:Guid}")] public ActionResult GetById(Guid id) { var contact = repository.GetContactById(id); if (contact == null) return NotFound(); return Ok(contact); } [HttpPost("{id:Guid}")] public ActionResult Update(Guid id, [FromBody] Contact contact) { repository.UpdateContact(id, contact); return Ok(); } [HttpDelete("{id:Guid}")] public ActionResult Delete(Guid id) { var contact = repository.GetContactById(id); if (contact == null) return NotFound(); repository.DeleteContact(id); return Ok(); } [HttpPost("upload")] public async Task Upload(IFormFile file) { if (file == null || file.Length == 0) return BadRequest("Файл пустой."); using var stream = new MemoryStream(); await file.CopyToAsync(stream); string json = System.Text.Encoding.UTF8.GetString(stream.ToArray()); try { repository.LoadJSON(json); // репозиторий сам парсит JSON и обновляет список } catch (Exception ex) { return BadRequest("Ошибка при обработке JSON: " + ex.Message); } return Ok("Контакты успешно загружены."); } [HttpGet("download")] public IActionResult Download() { string json = repository.SaveJSON(); // репозиторий формирует JSON строку byte[] bytes = System.Text.Encoding.UTF8.GetBytes(json); return File( bytes, "application/json", "contacts.json" ); } } }