using AutoMapper; using AutoMapper.QueryableExtensions; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using OnlyPrompt.Backend.ApiModels.UserProfile; using OnlyPrompt.Backend.Database; using OnlyPrompt.Backend.Database.Models; using OnlyPrompt.Backend.Utils; namespace OnlyPrompt.Backend.Controllers { [ApiController] [Route("api/v1/profiles")] [Authorize(Roles = ModelConstants.UserRole)] public class ProfileController : BaseController { private static ValidationProblem SlugExistsProblem = TypedResults.ValidationProblem(new Dictionary { { nameof(UserProfileModel.Slug), new[] { "Slug already exists." } } }); public ProfileController(OnlyPromptContext db, IMapper mapper) : base(db, mapper) { } [HttpGet("{id}")] public async Task, Ok>> GetProfileAsync(Identifier id) { var userId = User.GetUserId(); var profile = await _db.UserProfiles.OfIdentifer(id) .Where(up => up.IsPublic || up.Id == userId) .ProjectTo(_mapper.ConfigurationProvider) .FirstOrDefaultAsync(); if (profile is null) return TypedResults.NotFound("Profile not found or is private."); return TypedResults.Ok(profile); } [HttpPut] public async Task, Ok>> UpdateProfileAsync([FromBody] ApiUpdateProfileRequest request) { var self = await GetUserProfileAsync(); if (self is null) return TypedResults.NotFound("Profile not found."); if (string.IsNullOrEmpty(request.Slug) == false) { if (await _db.UserProfiles.AnyAsync(up => up.Slug == request.Slug && up.Id != self.Id)) return SlugExistsProblem; self.Slug = request.Slug; } if(string.IsNullOrEmpty(request.AvatarUrl) == false) self.AvatarUrl = request.AvatarUrl; if(string.IsNullOrEmpty(request.Bio) == false) self.Bio = request.Bio; if(string.IsNullOrEmpty(request.Specialities) == false) self.Specialities = request.Specialities; if (string.IsNullOrEmpty(request.DisplayName) == false) self.DisplayName = request.DisplayName; self.IsPublic = request.IsPublic; await _db.SaveChangesAsync(); var result = _mapper.Map(self); return TypedResults.Ok(result); } } }