using System.Data; using System.Security.Cryptography; using Microsoft.AspNetCore.DataProtection; using System.Text.Json; using Dapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.Services.Context; namespace PlotLine.Controllers; [Authorize] public sealed class CharacterAttributesController(IProjectRepository projects,ICharacterRepository characters,IProjectCollaborationRepository collaboration,ICurrentUserService user,ISqlConnectionFactory connections,ContextWorkspaceNotifications notifications,IDataProtectionProvider protection) : Controller { [HttpGet] public async Task Directory(int projectId) { if(user.UserId is not int author)return Unauthorized(); var project=await projects.GetForUserAsync(projectId,author); if(project is null)return NotFound(); var owner=await collaboration.GetOwnerUserIdAsync(projectId); var definitions=CharacterQuickAttributes.Definitions(owner.HasValue?await characters.ListSexValuesAsync(owner.Value):[]); using var db=connections.CreateConnection(); var rows=await db.QueryAsync("dbo.Character_QuickAttributes_Read",new {ProjectID=projectId,UserID=author},commandType:CommandType.StoredProcedure); return Json(new {canEdit=ContextEditPolicy.CanEdit(project),groups=definitions.Select(g=>new {g.Id,g.Label,values=g.Values.Select(v=>new {v.Value,v.Label,v.Tone,v.Icon,path=ApplicationRibbon.Icon(v.Icon).IconPath})}),characters=rows.Select(CharacterQuickAttributes.Snapshot)}); } public sealed record UndoChange(int Id,string Value,string? Sex,string Version); public sealed record UndoReceipt(int User,int ProjectId,string Attribute,UndoChange[] Changes,DateTime Expires); public sealed record UndoRequest(string Token); private sealed class PreviousValue {public int Id{get;set;}public string Value{get;set;}="";public string? Sex{get;set;}} [HttpPost,ValidateAntiForgeryToken] public async Task Undo([FromBody] UndoRequest request) { if(user.UserId is not int author)return Unauthorized(); if(!ModelState.IsValid||request is null||request.Token is null||request.Token.Length>1000000)return BadRequest("Undo is unavailable."); try { var receipt=JsonSerializer.Deserialize(protection.CreateProtector("CharacterQuickAttributes.Undo.v1").Unprotect(request.Token)); if(receipt is null||receipt.User!=author||receipt.Expires Assign([FromBody] CharacterQuickAssignment input) { if(user.UserId is not int author)return Unauthorized(); if(!ModelState.IsValid||input is null||input.Changes is null||input.Changes.Any(c=>c is null)||input.Changes.Length is <1 or >2000||input.Changes.Select(c=>c.Id).Distinct().Count()!=input.Changes.Length)return BadRequest("Choose a distinct character selection."); if(input.Attribute is not ("importance" or "life" or "sex" or "quickAdd"))return BadRequest("Unknown attribute."); if(input.Changes.Any(c=>c.Value?.Length>100||!DateTime.TryParse(c.Version,out _)))return BadRequest("Invalid assignment."); return await Execute(input.ProjectId,input.Attribute,input.Changes.Select(c=>new UndoChange(c.Id,c.Value??"",null,c.Version)).ToArray(),false); } private async Task Execute(int projectId,string attribute,UndoChange[] changes,bool restore) { var author=user.UserId!.Value; try { using var db=connections.CreateConnection(); using var result=await db.QueryMultipleAsync("dbo.Character_QuickAttributes_Assign",new {ProjectID=projectId,UserID=author,Attribute=attribute,Changes=JsonSerializer.Serialize(changes),Restore=restore},commandType:CommandType.StoredProcedure); var rows=(await result.ReadAsync()).ToArray(); var before=(await result.ReadAsync()).ToArray(); string? undoToken=null; if(rows.Length>0) { var versions=rows.ToDictionary(c=>c.CharacterID,c=>c.UpdatedDate.ToString("O")); undoToken=protection.CreateProtector("CharacterQuickAttributes.Undo.v1").Protect(JsonSerializer.Serialize(new UndoReceipt(author,projectId,attribute,before.Select(c=>new UndoChange(c.Id,c.Value,c.Sex,versions[c.Id])).ToArray(),DateTime.UtcNow.AddMinutes(10)))); await notifications.Invalidate(author,projectId:projectId,kind:"characters"); } return Json(new {saved=true,characters=rows.Select(CharacterQuickAttributes.Snapshot),undoToken}); } catch(SqlException e) when(e.Number is 51010 or 51011 or 51012){return StatusCode(e.Number==51010?403:409,new {message=e.Number==51011?"Characters changed in another window. Refresh their attributes and try again.":"The selection or attribute value is no longer available."});} } }