using System.Data; using System.Text.Json; using Dapper; using PlotLine.Models.Investigations; using PlotLine.Services.Investigations; namespace PlotLine.Data; public interface IInvestigationRepository {Task Catalogue(string? version=null);Task Publish(string json,string actor);Task> List(int user,int book);Task Read(int user,int book,Guid id);Task Save(Investigation row,int expected,string operation,Evaluation result);Task Replay(int user,int book,Guid id);} public sealed class InvestigationRepository(ISqlConnectionFactory factory):IInvestigationRepository { public async Task Catalogue(string? version=null){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync("dbo.WriterInvestigationCatalogue",new{Action="read",Version=version},commandType:CommandType.StoredProcedure);return json==null?null:CatalogueValidator.Parse(json);} public async Task Publish(string json,string actor){var c=CatalogueValidator.Parse(json);using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterInvestigationCatalogue",new{Action="publish",c.Version,Json=json,Actor=actor},commandType:CommandType.StoredProcedure);} public async Task> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync("dbo.WriterInvestigation",new{Action="list",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).Select(Parse).ToArray();} public async Task Read(int user,int book,Guid id){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync("dbo.WriterInvestigation",new{Action="read",UserID=user,BookID=book,ID=id},commandType:CommandType.StoredProcedure);return json==null?null:Parse(json);} public async Task Save(Investigation row,int expected,string operation,Evaluation result){using var db=factory.CreateConnection();row.Version=expected+1;await db.ExecuteAsync("dbo.WriterInvestigation",new{Action="save",row.UserID,row.ProjectID,row.BookID,row.ID,row.CatalogueVersion,ExpectedVersion=expected,Json=JsonSerializer.Serialize(row,CatalogueValidator.Json),Event=JsonSerializer.Serialize(new{operation,state=row,evaluation=result},CatalogueValidator.Json)},commandType:CommandType.StoredProcedure);} public async Task Replay(int user,int book,Guid id){using var db=factory.CreateConnection();return(await db.QueryAsync("dbo.WriterInvestigation",new{Action="events",UserID=user,BookID=book,ID=id},commandType:CommandType.StoredProcedure)).ToArray();} static Investigation Parse(string json)=>JsonSerializer.Deserialize(json,CatalogueValidator.Json)!; }