using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; namespace PlotLine.Controllers; [Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public sealed class NameVerificationController(INameVerification verification,INameManuscriptRepository manuscripts,IProjectRepository projects,ICurrentUserService user,ILogger logger):Controller { private int Author=>user.UserId??throw new UnauthorizedAccessException(); private bool Valid(int project,string? name)=>ModelState.IsValid&&project>0&&!string.IsNullOrWhiteSpace(name)&&name.Length<=120; [HttpGet] public async Task Estimate(int projectId,string name,bool retryInterrupted=false) { if(!Valid(projectId,name))return BadRequest(new{message="Choose a valid selected name."}); try{var result=await verification.Estimate(Author,projectId,name,retryInterrupted);return Json(new{quote=AiQuotePresentation.From(result.Quote,Url.Action("Subscription","ManageAccount")!),result.PlanToken,result.Cached,result.RequiresAi,result.TextualMatches,result.MatchesExact,result.PlannedContexts,result.PlannedMatches,result.Complete,result.Summary});} catch(UnauthorizedAccessException){return StatusCode(403,new{message="Name verification requires access to this series and project editing permission."});} catch(Exception error)when(error is SqlException or ArgumentException or InvalidOperationException){logger.LogWarning(error,"Name verification preview unavailable for project {ProjectID}.",projectId);return BadRequest(new{message="The verification preview could not be prepared. No AI request or credit reservation was made."});} } [HttpPost,ValidateAntiForgeryToken] public async Task Execute([FromBody]NameVerificationRequest request) { if(request is null||!ModelState.IsValid)return BadRequest(new{message="Review the verification scope and cost first."}); try{var result=await verification.Execute(Author,request,HttpContext.RequestAborted);return StatusCode(result.Processing?202:200,new{result.NameVerificationID,result.Processing,result.Cached,result.Complete});} catch(UnauthorizedAccessException){return StatusCode(403,new{message="Verification access is unavailable. Previously saved results remain readable where you have series access."});} catch(OperationCanceledException){return StatusCode(408,new{message="Verification stopped. Check saved results before retrying; any usable partial findings are marked incomplete."});} catch(Exception error)when(error is ArgumentException or InvalidOperationException or SqlException or HttpRequestException or System.Text.Json.JsonException){logger.LogWarning(error,"Name verification did not complete.");return Conflict(new{message=error is ArgumentException?error.Message:"Verification could not finish. Review the current scope, policy and allowance before retrying. Previously saved results are preserved; abandoned reservations recover automatically."});} } [HttpGet] public async Task Result(int projectId,string name) { if(!Valid(projectId,name))return BadRequest(); try{var result=await verification.Read(Author,projectId,name);return result is null?PartialView("_NameVerificationEmpty"):PartialView("_NameVerification",result);}catch(UnauthorizedAccessException){return Forbid();} } [HttpGet] public async Task Findings(int projectId,string name,int verificationId,int offset=0,bool includeOrdinary=false) { if(!Valid(projectId,name)||offset<0||offset>NameTextMatcher.MaximumReferences)return BadRequest(); try{var result=await verification.Read(Author,projectId,name);if(result is null)return NotFound();if(result.NameVerificationID!=verificationId)return Conflict("Saved verification changed. Refresh its summary.");return PartialView("_NameVerificationFindings",new NameVerificationFindingsViewModel(result,offset,includeOrdinary));}catch(UnauthorizedAccessException){return Forbid();} } [HttpGet] public async Task Textual(int projectId,string name,int offset=0) { if(!Valid(projectId,name)||offset<0||offset>NameTextMatcher.MaximumReferences)return BadRequest(); try{if(await projects.GetForUserAsync(projectId,Author) is null)return Forbid();return PartialView("_NameTextOccurrences",new NameTextOccurrencesViewModel(await manuscripts.Search(Author,projectId,name),offset));} catch(UnauthorizedAccessException){return Forbid();}catch(SqlException error){logger.LogWarning(error,"Textual name lookup unavailable for project {ProjectID}.",projectId);return StatusCode(503,"The textual lookup could not finish. No AI request was made.");} } }