package com.example.orderworkflowservice;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.teaql.core.UserContext;
import java.nio.file.*;import java.util.*;
/** Tenant-scoped stock reservation facade; input never controls identity. */
public final class OrderCheck {
 static final ObjectMapper JSON=new ObjectMapper();static final String SEED="Seed stock reservation fixture",RESERVE="Reserve Order inventory atomically";
 record Session(String actor,String tenant,String buyer){};static final Map<String,Session> TRUSTED=Map.of("a",new Session("ACTOR-A","TENANT-A","BUYER-A"),"b",new Session("ACTOR-B","TENANT-A","BUYER-B"),"c",new Session("ACTOR-C","TENANT-B","BUYER-A"));
 static class Denied extends RuntimeException{Denied(String c){super(c);}}
 static Map<String,Object> obj(Object... p){var r=new LinkedHashMap<String,Object>();for(int i=0;i<p.length;i+=2)r.put((String)p[i],p[i+1]);return r;}
 static long num(Object n){return ((Number)n).longValue();}
 static void validate(String token,Map<String,Object> r){
  if(!TRUSTED.containsKey(token))throw new Denied("UNAUTHENTICATED");if(r.keySet().stream().anyMatch(Set.of("tenant","buyer","actor","permissions","policy","userContext")::contains))throw new Denied("FORGED_SCOPE");
  if(!r.keySet().equals(Set.of("requestKey","orderNumber","sku","quantity"))||!(r.get("quantity") instanceof Integer||r.get("quantity") instanceof Long)||num(r.get("quantity"))<1||num(r.get("quantity"))>10||!(r.get("requestKey") instanceof String k)||!k.matches("[A-Z0-9-]{1,64}"))throw new Denied("INVALID_REQUEST");for(String f:List.of("orderNumber","sku"))if(!(r.get(f) instanceof String s)||s.isEmpty()||s.length()>64)throw new Denied("INVALID_REQUEST");
 }
 static boolean conflict(Exception e){return e instanceof io.teaql.core.ConcurrentModifyException;}
 static Map<String,Object> result(String code,Object id,int attempts,List<String> reasons){return obj("code",code,"receiptId",id,"attempts",attempts,"conflicts",reasons.size(),"conflictReasons",List.copyOf(reasons));}
 static void barrier(Object ready)throws Exception{String folder=System.getenv("ORDER_BARRIER");if(folder==null)return;Path f=Path.of(folder);String worker=System.getenv("ORDER_WORKER");Path temp=f.resolve(worker+".tmp");Files.writeString(temp,JSON.writeValueAsString(ready));Files.move(temp,f.resolve(worker+".ready"),StandardCopyOption.ATOMIC_MOVE);long end=System.nanoTime()+45_000_000_000L;while(!Files.exists(f.resolve("release"))){if(System.nanoTime()>end)throw new IllegalStateException("Barrier timeout");Thread.sleep(10);}}
 static Object handle(UserContext context,String token,Map<String,Object> r)throws Exception{
  var reasons=new ArrayList<String>();int attempts=0;
  try{validate(token,r);var s=TRUSTED.get(token);String key=(String)r.get("requestKey"),number=(String)r.get("orderNumber"),sku=(String)r.get("sku");int qty=(int)num(r.get("quantity"));
   for(int attempt=0;attempt<3;attempt++){
    attempts++;var roots=Q.commercePlatforms().withTenantKeyIs(s.tenant())
     .limit(2).comment("Load trusted tenant reservation aggregate").purpose("Bind Order inventory and receipt to server session").executeForList(context);
    if(roots.size()!=1)throw new IllegalStateException("Invalid trusted root");var root=roots.get(0);long rootId=E.commercePlatform(root).getId().eval();var receipts=Q.stockReservations().filterByCommercePlatform(rootId).withBuyerReferenceIs(s.buyer()).withRequestKeyIs(key).limit(2).comment("Read scoped reservation receipt").purpose("Bind request key to trusted tenant and buyer").executeForList(context);if(receipts.size()>1)throw new IllegalStateException("Duplicate persisted request key");
    if(!receipts.isEmpty()){var e=E.stockReservation(receipts.get(0));boolean same=Objects.equals(e.getOrderNumber().eval(),number)&&Objects.equals(e.getSkuCode().eval(),sku)&&e.getQuantity().eval()==qty;return result(same?"REPLAY":"IDEMPOTENCY_CONFLICT",same?e.getId().eval():null,attempts,reasons);}
    var orders=Q.customerOrders().filterByCommercePlatform(rootId).withBuyerReferenceIs(s.buyer()).withOrderNumberIs(number).limit(2).comment("Load authorized complete Order").purpose("Reserve only the trusted buyer Order").executeForList(context);var stocks=Q.inventory().filterByCommercePlatform(rootId).withSkuCodeIs(sku).limit(2).comment("Load tenant SKU inventory").purpose("Reserve tenant-owned inventory").executeForList(context);if(orders.size()!=1||stocks.size()!=1)throw new Denied("NOT_FOUND");var order=orders.get(0);var stock=stocks.get(0);var oe=E.customerOrder(order);var se=E.inventory(stock);
    if(oe.getOrderStatus().eval().getId()!=1001)throw new Denied("ORDER_NOT_DRAFT");
    var items=Q.orderItems().filterByCustomerOrder(oe.getId().eval()).limit(2).comment("Validate complete bounded Order items").purpose("Reject mismatched reservation quantity or SKU").executeForList(context);
    if(items.size()!=1||!Objects.equals(E.orderItem(items.get(0)).getSkuCode().eval(),sku)||E.orderItem(items.get(0)).getQuantity().eval()!=qty)throw new Denied("INVALID_ORDER_ITEMS");
    int available=se.getAvailableQuantity().eval(),reserved=se.getReservedQuantity().eval();if(available<0||reserved<0)throw new IllegalStateException("Invalid inventory");if(available<qty)throw new Denied("OUT_OF_STOCK");
    if(attempt==0)barrier(obj("pid",ProcessHandle.current().pid(),"session",token,"requestKey",key,"orderNumber",number,"quantity",qty,"rootVersion",E.commercePlatform(root).getVersion().eval(),"inventoryVersion",se.getVersion().eval(),"available",available,"orderVersion",oe.getVersion().eval()));
    root.updateReservationSequence(E.commercePlatform(root).getReservationSequence().eval()+1);order.updateOrderStatusToConfirmed();stock.updateAvailableQuantity(available-qty);stock.updateReservedQuantity(reserved+qty);
    var receipt=Q.stockReservations().comment("Create immutable scoped reservation receipt").purpose("Commit request idempotency with inventory").newEntity(context);receipt.updateCommercePlatform(root);receipt.updateCustomerOrder(order);receipt.updateInventory(stock);receipt.updateRequestKey(key);receipt.updateBuyerReference(s.buyer());receipt.updateQuantity(qty);receipt.updateOrderNumber(number);receipt.updateSkuCode(sku);
    try{
     // Explicit native transaction fixes write order: the receipt fault must occur last.
     var executor=((io.teaql.runtime.DefaultUserContext)context).getRuntime().getRegistry().resolveMutationExecutor("default");
     if(!(executor instanceof io.teaql.core.TransactionExecutor transaction))throw new IllegalStateException("Native transaction capability required");
     transaction.executeInTransaction(context,()->{if(FAULT!=null)FAULT.event("BEGIN_OK");root.auditAs(RESERVE).save(context);order.auditAs(RESERVE).save(context);stock.auditAs(RESERVE).save(context);if(FAULT!=null)FAULT.gate("after-inventory");receipt.auditAs(RESERVE).save(context);if(FAULT!=null){FAULT.gate("before-commit");FAULT.event("COMMIT_START");}return null;});
    }catch(Exception error){if(error.toString().contains("ORDER_PROVIDER_TEST_ABORT")){var value=result("PROVIDER_FAILED",null,attempts,reasons);value.put("reason",error.toString());return value;}if(!conflict(error))throw error;reasons.add("Optimistic version conflict: "+error.toString());continue;}
    var saved=Q.stockReservations().filterByCommercePlatform(E.commercePlatform(root).getId().eval()).withBuyerReferenceIs(s.buyer()).withRequestKeyIs(key).limit(2).comment("Read committed reservation receipt").purpose("Return durable idempotency identity").executeForList(context);if(saved.size()!=1)throw new IllegalStateException("Missing receipt");return result("RESERVED",E.stockReservation(saved.get(0)).getId().eval(),attempts,reasons);
   }return result("CONFLICT_LIMIT",null,attempts,reasons);
  }catch(Denied e){return result(e.getMessage(),null,attempts,reasons);}
 }
 @SuppressWarnings("unchecked") static void seed(UserContext context)throws Exception{
  var f=JSON.readValue(Files.readString(Path.of(System.getenv("ORDER_FIXTURE"))),Map.class);var roots=Q.commercePlatforms().limit(2).comment("Read initialized stock root").purpose(SEED).executeForList(context);if(roots.size()!=1)throw new IllegalStateException("Expected initialized root");int n=0;
  for(var t:(List<Map<String,Object>>)f.get("tenants")){String tenant=(String)t.get("key");var root=n++==0?roots.get(0):Q.commercePlatforms().comment("Create tenant").purpose(SEED).newEntity(context);root.updateName("Tenant "+tenant.charAt(tenant.length()-1));root.updateTenantKey(tenant);root.updateReservationSequence(0);root.auditAs(SEED).save(context);
   for(int k=0;k<2;k++){var stock=Q.inventory().comment("Create SKU inventory").purpose(SEED).newEntity(context);stock.updateCommercePlatform(root);stock.updateSkuCode((String)f.get(k==0?"sku":"controlSku"));stock.updateAvailableQuantity((int)num(k==0?t.get("available"):f.get("controlAvailable")));stock.updateReservedQuantity(0);stock.updateWarehouseNote("Initial warehouse stock");stock.auditAs(SEED).save(context);}
   for(String buyer:(List<String>)f.get("buyers"))for(var d:(List<Map<String,Object>>)f.get("orders")){int qty=(int)num(d.get("quantity")),price=(int)num(f.get("unitPriceMinor"));var o=Q.customerOrders().comment("Create stock Order").purpose(SEED).newEntity(context);o.updateCommercePlatform(root);o.updateOrderStatusToDraft();o.updateOrderNumber((String)d.get("number"));o.updateBuyerReference(buyer);o.updateCurrencyCode("USD");o.updateTotalMinor(qty*price);o.updateOrderNote("Stock reservation fixture order");o.auditAs(SEED).save(context);
    var i=Q.orderItems().comment("Create complete Order line").purpose(SEED).newEntity(context);i.updateCustomerOrder(o);i.updateSkuCode((String)f.get("sku"));i.updateProductName((String)f.get("sku"));i.updateQuantity(qty);i.updateUnitPriceMinor(price);i.updateLineTotalMinor(qty*price);i.auditAs(SEED).save(context);}
  }
 }
 static FaultGate FAULT;
 static class FaultGate{
  boolean active=true;final String mode=System.getenv("ORDER_FAULT_MODE");final Path folder=Path.of(System.getenv("ORDER_FAULT_BARRIER"));final List<Object> events=new ArrayList<>();
  void event(String name){if(active){var e=obj("event",name);events.add(e);try{System.out.println("ORDER_FAULT_EVENT "+JSON.writeValueAsString(e));}catch(Exception x){throw new RuntimeException(x);}}}
  void publish(String name,Object value){try{Path temp=folder.resolve(name+".tmp");Files.writeString(temp,JSON.writeValueAsString(value));Files.move(temp,folder.resolve(name+".json"),StandardCopyOption.ATOMIC_MOVE);}catch(Exception e){throw new RuntimeException(e);}}
  void waitFor(String name){long end=System.nanoTime()+45_000_000_000L;while(!Files.exists(folder.resolve(name))){if(System.nanoTime()>end)throw new IllegalStateException("Fault barrier timeout");try{Thread.sleep(10);}catch(InterruptedException e){Thread.currentThread().interrupt();throw new java.util.concurrent.CancellationException("Native request thread interrupted");}}}
  void gate(String point){if(!active||point.equals("after-inventory")&&!Set.of("cancel","provider").contains(mode)||point.equals("before-commit")&&!Set.of("commit","control").contains(mode))return;event("WAIT");publish("ready",obj("pid",ProcessHandle.current().pid(),"mode",mode,"point",point));if(mode.equals("cancel")){waitFor("cancel");Thread.currentThread().interrupt();try{Thread.sleep(1);}catch(InterruptedException e){Thread.currentThread().interrupt();throw new java.util.concurrent.CancellationException("Native request thread interrupted after inventory");}}else waitFor("release");}
 }
 @SuppressWarnings("unchecked") static void faultRun(UserContext context)throws Exception{
  var gate=new FaultGate();FAULT=gate;var request=obj("requestKey","REQ-FAULT","orderNumber","ORD-STOCK-001","sku","SKU-WIDGET","quantity",4);var registry=((io.teaql.runtime.DefaultUserContext)context).getRuntime().getRegistry();var originalProvider=registry.resolveMutationExecutor("default");var originalContext=context;System.out.println("ORDER_FAULT_BEGIN");Map<String,Object> first;
  try{if(gate.mode.equals("pre-cancel")){Thread.currentThread().interrupt();try{Thread.sleep(1);}catch(InterruptedException e){Thread.currentThread().interrupt();throw new java.util.concurrent.CancellationException("Native request cancelled before admission");}}var value=(Map<String,Object>)handle(context,"a",request);if(gate.mode.equals("control"))gate.event("COMMIT_OK");first=obj("code",value.get("code"),"result",value);}
  catch(Exception e){gate.event(gate.mode.equals("pre-cancel")?"REQUEST_CANCELLED":gate.mode.equals("commit")?"COMMIT_ERROR":"TRANSACTION_RETURNED_ERROR");e.printStackTrace(System.out);first=obj("code",e instanceof java.util.concurrent.CancellationException?"CANCELLED":gate.mode.equals("commit")?"COMMIT_FAILED":"UNEXPECTED_ERROR","type",e.getClass().getName(),"error",e.toString()+"; cause="+e.getCause());}
  finally{Thread.interrupted();}
  first.putAll(obj("pid",ProcessHandle.current().pid(),"providerIdentity",System.identityHashCode(originalProvider),"contextIdentity",System.identityHashCode(context),"events",List.copyOf(gate.events),"interruptCleared",!Thread.currentThread().isInterrupted()));gate.publish("failed",first);gate.active=false;gate.waitFor("recovery");System.out.println("ORDER_FAULT_RECOVERY");var recovery=handle(context,"a",request);System.out.println("ORDER_FAULT_RESULT "+JSON.writeValueAsString(obj("mode",gate.mode,"first",first,"recovery",recovery,"sameProvider",registry.resolveMutationExecutor("default")==originalProvider,"sameContext",context==originalContext,"tasksJoined",!Thread.currentThread().isInterrupted())));
 }
 public static void run(String phase,UserContext context)throws Exception{
  if(phase.equals("seed"))seed(context);else if(phase.equals("fault"))faultRun(context);else if(!phase.equals("bootstrap"))throw new IllegalArgumentException("Unknown phase");System.out.println("ORDER_OK phase="+phase);
 }
}
