using System.Security.Claims; using System.Security.Cryptography; using System.Text; using MongoDB.Driver; namespace GuestOps.Web; public static class AutoReplyEndpoints { public static void Map(RouteGroupBuilder api,bool preview) { var group=api.MapGroup("/auto-replies").RequireRateLimiting("pms"); group.MapGet("/status",(AutoReplyWork work)=>Results.Ok(new{liveConfigured=!preview&&work.LiveConfigured,preview,questions=FaqMatcher.Questions,dailyLimit=20})); group.MapGet("/rules",async(HttpContext c,IStore store)=>Results.Ok(await store.List(Session.Hotel(c)))); group.MapGet("/history",async(HttpContext c,IStore store)=>Results.Ok((await store.List(Session.Hotel(c))).Where(m=>m.AutoReplyCheckedAt!=null).OrderByDescending(m=>m.AutoReplyCheckedAt).Select(m=>new{m.Id,m.Subject,m.From,m.AutoReplyCheckedAt,m.AutoReplyMatched,m.AutoReplyDetail,delivery=m.Delivery?.State}))); group.MapPost("/test",async(AutoTestInput input,HttpContext c,AutoReplyWork work)=>{ if(!Input.Text(input.Subject,0,200)||!Input.Text(input.Body,1,2000))return Results.BadRequest();return Results.Ok(await work.Test(Session.Hotel(c),input.Subject,input.Body)); }).RequireAuthorization("Owner"); group.MapPost("/evaluate",async(AutoEvaluationInput input,HttpContext c,AutoReplyWork work)=>{ if(input.Cases is not {Length:>=1 and <=100} cases||cases.Select(x=>x.Id).Distinct(StringComparer.Ordinal).Count()!=cases.Length||cases.Any(x=>!Input.Text(x.Id,1,80)||!Input.Text(x.Subject,0,200)||!Input.Text(x.Body,1,2000)||x.ExpectedKnowledgeId.Length>80))return Results.BadRequest(); var results=await work.Evaluate(Session.Hotel(c),cases);return Results.Ok(new{total=results.Length,passed=results.Count(x=>x.Passed),falsePositives=results.Count(x=>!x.ExpectedMatch&&x.ActualMatch),falseNegatives=results.Count(x=>x.ExpectedMatch&&!x.ActualMatch),results}); }).RequireAuthorization("Owner"); group.MapPut("/rules/{question:int}",async(int question,AutoRuleInput input,HttpContext c,IStore store)=>{ if(question<0||question>=FaqMatcher.Questions.Length||input.Question!=FaqMatcher.Questions[question])return Results.BadRequest(); var hotel=Session.Hotel(c);var key=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(hotel+":"+question))).ToLowerInvariant()[..32]; var answer=await store.Get(hotel,input.KnowledgeId);if(answer?.Approved!=true)return Results.BadRequest(new{error="Choose an approved answer from this hotel."}); var rule=await store.Get(hotel,key);bool exists=rule!=null; if(!exists&&input.Version!=0)return Input.Conflict(); rule??=new AutoReplyRule{Id=key,HotelId=hotel};rule.Question=input.Question;rule.KnowledgeId=answer.Id;rule.KnowledgeVersion=answer.Version;rule.Enabled=input.Enabled;rule.ApprovedBy=c.User.FindFirstValue(ClaimTypes.NameIdentifier)!;rule.Version=input.Version+1; if(exists){if(!await store.Replace(hotel,key,input.Version,rule))return Input.Conflict();} else{try{await store.Insert(rule);}catch(MongoWriteException ex) when(ex.WriteError.Category==ServerErrorCategory.DuplicateKey){return Input.Conflict();}} await Session.Audit(store,c,"Reviewed FAQ automatic reply rule: "+rule.Question);return Results.Ok(rule); }).RequireAuthorization("Owner"); group.MapPut("/mode",async(AutoModeInput input,HttpContext c,IStore store,AutoReplyWork work,GoogleMailbox google)=>{ if(input.Mode is not ("Off" or "Test" or "Live"))return Results.BadRequest(); var hotel=await store.Get(Session.Hotel(c),Session.Hotel(c));if(hotel==null)return Results.NotFound(); if(input.Mode=="Live"&&(preview||!work.LiveConfigured||!google.SendingConfigured||!hotel.StaffSendingEnabled||!input.AcceptanceConfirmed))return Results.BadRequest(new{error="Live mode requires administrator enablement, Google sending, hotel sending and confirmed test-mode acceptance."}); hotel.AutoReplyMode=input.Mode;hotel.AutoReplyEpoch=Guid.NewGuid().ToString("N");hotel.AutoReplySince=DateTime.UtcNow;hotel.Version=input.Version+1; if(!await store.Replace(hotel.HotelId,hotel.Id,input.Version,hotel))return Input.Conflict();await Session.Audit(store,c,"Set FAQ automation mode: "+input.Mode);return Results.Ok(hotel); }).RequireAuthorization("Owner"); } }