using AutoMapper; using Diligent.WebAPI.Business.MongoServices; using Diligent.WebAPI.Data.Entities; using Diligent.WebAPI.Host.Exceptions; using Diligent.WebAPI.Host.MongoDTOs.InsuranceCompanyMongo; using Diligent.WebAPI.Host.MongoDTOs.InsurerMongo; using Microsoft.AspNetCore.Mvc; namespace Diligent.WebAPI.Host.MongoController { [ApiVersion("1.0")] [ApiController] [Route("v{version:apiVersion}/[controller]")] public class InsurerController : ControllerBase { private readonly InsurerService _insurerService; private readonly InsuranceCompanyService _insuranceCompanyService; private readonly IMapper _mapper; public InsurerController(IMapper mapper, InsurerService insurerService, InsuranceCompanyService insuranceCompanyService) { _mapper = mapper; _insurerService = insurerService; _insuranceCompanyService = insuranceCompanyService; } [HttpGet] public async Task GetAll() { var insurers = _mapper.Map>(await _insurerService.GetInsurersAsync()); return Ok(insurers); } [HttpGet("{id:length(24)}")] public async Task> Get(string id) { var insurer = await _insurerService.GetByIdAsync(id); if (insurer is null) { throw new NotFoundException("Insurer not found"); } var returnInsurer = _mapper.Map(insurer); if(returnInsurer.InsuranceCompanyId != null) { returnInsurer.InsuranceCompany = _mapper.Map(await _insuranceCompanyService.GetByIdAsync(returnInsurer.InsuranceCompanyId)); } return returnInsurer; } [HttpPost] public async Task Post(InsurerSaveDTO request) { var insurer = _mapper.Map(request); await _insurerService.CreateInsurer(insurer); var returnInsurer = _mapper.Map(insurer); if(returnInsurer.InsuranceCompanyId != null) { var insuranceCompany = _mapper.Map(await _insuranceCompanyService.GetByIdAsync(returnInsurer.InsuranceCompanyId)); returnInsurer.InsuranceCompany = insuranceCompany; } return CreatedAtAction(nameof(Get), new { id = insurer.Id }, returnInsurer); } [HttpPut("{id:length(24)}")] public async Task Update(string id, InsurerMongo request) { var insurer = await _insurerService.GetByIdAsync(id); if (insurer is null) { throw new NotFoundException("Insurer not found"); } request.Id = insurer.Id; await _insurerService.UpdateInsurer(id, request); return Ok(); } [HttpDelete("{id:length(24)}")] public async Task Delete(string id) { var insurer = await _insurerService.GetByIdAsync(id); if (insurer is null) { throw new NotFoundException("Insurer not found"); } await _insurerService.DeleteInsurerAsync(id); return Ok(); } } }