using CodeLiturgy.Data.Auth.Context.Users; using CodeLiturgy.Data.Application; using CodeLiturgy.Domain; using CodeLiturgy.Views.Augeas; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace CodeLiturgy.Views.Controllers { /// /// Controller responsible for managing websites. /// [Route("api/sites")] [ApiController] [Authorize] public class SitesApiController : ControllerBase { private ApplicationUserManager _userManager; private ILogger _logger; private readonly SiteDbContext _siteDbContext; private readonly AugeasManager _augeasManager; /// /// Sites controller constructor. /// /// /// /// /// public SitesApiController( ApplicationUserManager userManager, ILogger logger, SiteDbContext siteDbContext, AugeasManager augeasManager) { _logger = logger; _userManager = userManager; _siteDbContext = siteDbContext; _augeasManager = augeasManager; } /// /// Gets the sites stored in the database. /// /// /// /// /// [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] public async Task GetSites( int skip = 0, int take = 50, int orderDir = 1) { var result = await _siteDbContext .Sites.Skip(skip) .Take(take) .ToListAsync(); return Ok(result); } /// /// Gets a site by Id. /// /// Site id. /// [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [HttpGet("{siteId}", Name = nameof(GetSiteById))] public async Task GetSiteById(string siteId) { var site = await _siteDbContext.Sites.Where(x => x.Id == siteId).FirstOrDefaultAsync(); if (site != null) { return Ok(site); } return new NotFoundResult(); } /// /// Adds a site to the database. /// /// /// [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status406NotAcceptable)] [HttpPost] public async Task AddSite(SiteCreate siteToCreate) { var site = new Site() { Domain = siteToCreate.Domain, CreatedDate = DateTime.Today, SiteType = siteToCreate.SiteType }; _siteDbContext.Sites.Add(site); var success = await _siteDbContext.SaveChangesAsync() >= 0; if (!success) return new BadRequestResult(); return CreatedAtRoute(nameof(GetSiteById), new {Id = site.Id}, site); } } }