using Emergence.api.Models; using Emergence.models; using Emergence.services.Interface; using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Mvc; using System.Text.Json.Serialization; namespace Emergence.api.Controllers; [ApiController] [Route("[controller]")] public class TenantController : ControllerBase { private readonly ITenantService _tenantService; public TenantController(ITenantService tenantService) { _tenantService = tenantService; } [HttpGet(Name = "GetTenants")] public async Task>, NotFound>> GetTenants() { var tenants = await _tenantService.GetAllAsync(); if (tenants is null) { return TypedResults.NotFound(); } return TypedResults.Ok(tenants); } [HttpGet("{id}", Name = "GetTenantById")] public async Task, NotFound, BadRequest>> GetTenantById(Guid id) { var tenant = await _tenantService.GetByIdAsync(id); if (tenant is null) { return TypedResults.NotFound(); } return TypedResults.Ok(tenant); } [HttpPost(Name = "CreateTenant")] public async Task, Conflict, BadRequest, UnprocessableEntity>> Create(TenantModel tenant) { if (tenant == null || !ModelState.IsValid) return TypedResults.BadRequest(new ValidationProblemResult(ModelState)); if (tenant.Id.HasValue && tenant.Id.Value != Guid.Empty && _tenantService.GetByIdAsync(tenant.Id.Value).Result != null) return TypedResults.Conflict(new ErrorDetailResults($"Tenant already exists", $"Tenant with the id: {tenant.Id} already exists")); var newTenant = await _tenantService.CreateAsync(tenant); if (newTenant is null) { return TypedResults.UnprocessableEntity(new ErrorDetailResults($"Tenant failed to create", $"The new tenant failed to create. Please try again.")); } return TypedResults.Created($"/tenant/{newTenant.Id}", newTenant); } }