package main

import (
	"encoding/json"
	"fmt"
	"github.com/teaql/teaql-golang/runtime"
	"math"
	. "order-workflow-service-core-workspace/lib"
	"order-workflow-service-core-workspace/lib/commerce_platform"
	"order-workflow-service-core-workspace/lib/customer_order"
	"order-workflow-service-core-workspace/lib/inventory"
	"order-workflow-service-core-workspace/lib/order_item"
	"order-workflow-service-core-workspace/lib/stock_reservation"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"time"
)

type object = map[string]any

const seedReason = "Seed stock reservation fixture"
const reserveReason = "Reserve Order inventory atomically"

var trusted = map[string][3]string{"a": {"ACTOR-A", "TENANT-A", "BUYER-A"}, "b": {"ACTOR-B", "TENANT-A", "BUYER-B"}, "c": {"ACTOR-C", "TENANT-B", "BUYER-A"}}

func check(e error) {
	if e != nil {
		panic(e)
	}
}
func required[T any](v T, ok bool) T {
	if !ok {
		panic("Missing loaded value")
	}
	return v
}
func integer(v any) (int64, bool) {
	f, ok := v.(float64)
	return int64(f), ok && !math.IsNaN(f) && !math.IsInf(f, 0) && math.Trunc(f) == f && f <= 9007199254740991
}
func validate(token string, r object) string {
	if _, ok := trusted[token]; !ok {
		return "UNAUTHENTICATED"
	}
	for _, k := range []string{"tenant", "buyer", "actor", "permissions", "policy", "userContext"} {
		if _, ok := r[k]; ok {
			return "FORGED_SCOPE"
		}
	}
	if len(r) != 4 {
		return "INVALID_REQUEST"
	}
	for _, k := range []string{"requestKey", "orderNumber", "sku", "quantity"} {
		if _, ok := r[k]; !ok {
			return "INVALID_REQUEST"
		}
	}
	q, ok := integer(r["quantity"])
	if !ok || q < 1 || q > 10 {
		return "INVALID_REQUEST"
	}
	key, ok := r["requestKey"].(string)
	if !ok || !regexp.MustCompile(`^[A-Z0-9-]{1,64}$`).MatchString(key) {
		return "INVALID_REQUEST"
	}
	for _, k := range []string{"orderNumber", "sku"} {
		s, ok := r[k].(string)
		if !ok || len(s) < 1 || len(s) > 64 {
			return "INVALID_REQUEST"
		}
	}
	return ""
}
func conflict(err error) bool {
	t := strings.ToLower(err.Error())
	for _, w := range []string{"busy", "locked", "timeout"} {
		if strings.Contains(t, w) {
			return false
		}
	}
	for _, w := range []string{"version", "optimistic", "conflict", "stale", "authoritative persisted state"} {
		if strings.Contains(t, w) {
			return true
		}
	}
	return false
}
func barrier(ready object) {
	folder := os.Getenv("ORDER_BARRIER")
	if folder == "" {
		return
	}
	worker := os.Getenv("ORDER_WORKER")
	b, e := json.Marshal(ready)
	check(e)
	tmp := filepath.Join(folder, worker+".tmp")
	check(os.WriteFile(tmp, b, 0600))
	check(os.Rename(tmp, filepath.Join(folder, worker+".ready")))
	end := time.Now().Add(45 * time.Second)
	for {
		if _, e := os.Stat(filepath.Join(folder, "release")); e == nil {
			return
		}
		if time.Now().After(end) {
			panic("Barrier timeout")
		}
		time.Sleep(10 * time.Millisecond)
	}
}
func handle(context *runtime.UserContext, token string, r object) object {
	attempts := 0
	reasons := []string{}
	result := func(code string, id any) object {
		return object{"code": code, "receiptId": id, "attempts": attempts, "conflicts": len(reasons), "conflictReasons": append([]string{}, reasons...)}
	}
	if code := validate(token, r); code != "" {
		return result(code, nil)
	}
	session := trusted[token]
	tenant, buyer := session[1], session[2]
	key, number, sku := r["requestKey"].(string), r["orderNumber"].(string), r["sku"].(string)
	qty, _ := integer(r["quantity"])
	for attempt := 0; attempt < 3; attempt++ {
		attempts++
		roots, err := Q.CommercePlatforms().WithTenantKeyIs(tenant).SelectCustomerOrderListWith(Q.CustomerOrders().WithBuyerReferenceIs(buyer).WithOrderNumberIs(number).Limit(2)).SelectInventoryListWith(Q.Inventory().WithSkuCodeIs(sku).Limit(2)).SelectStockReservationListWith(Q.StockReservations().WithBuyerReferenceIs(buyer).WithRequestKeyIs(key).Limit(2)).Limit(2).Comment("Load trusted tenant reservation aggregate").Purpose("Bind Order inventory and receipt to server session").ExecuteForList(context)
		check(err)
		if len(roots.Data) != 1 {
			panic("Invalid trusted root")
		}
		root := roots.Data[0]
		receipts := root.StockReservationList().Items()
		if len(receipts) > 1 {
			panic("Duplicate persisted request key")
		}
		if len(receipts) == 1 {
			e := stock_reservation.NewStockReservationExpression(receipts[0])
			same := required(e.OrderNumber().Eval()) == number && required(e.SkuCode().Eval()) == sku && required(e.Quantity().Eval()) == qty
			if same {
				return result("REPLAY", required(e.Id().Eval()))
			}
			return result("IDEMPOTENCY_CONFLICT", nil)
		}
		orders, stocks := root.CustomerOrderList().Items(), root.InventoryList().Items()
		if len(orders) != 1 || len(stocks) != 1 {
			return result("NOT_FOUND", nil)
		}
		order, stock := orders[0], stocks[0]
		oe, se := customer_order.NewCustomerOrderExpression(order), inventory.NewInventoryExpression(stock)
		if required(oe.OrderStatusId().Eval()) != 1001 {
			return result("ORDER_NOT_DRAFT", nil)
		}
		items, err := Q.OrderItems().WithCustomerOrderIs(required(oe.Id().Eval())).Limit(2).Comment("Validate complete bounded Order items").Purpose("Reject mismatched reservation quantity or SKU").ExecuteForList(context)
		check(err)
		if len(items.Data) != 1 {
			return result("INVALID_ORDER_ITEMS", nil)
		}
		ie := order_item.NewOrderItemExpression(items.Data[0])
		if required(ie.SkuCode().Eval()) != sku || required(ie.Quantity().Eval()) != qty {
			return result("INVALID_ORDER_ITEMS", nil)
		}
		available, reserved := required(se.AvailableQuantity().Eval()), required(se.ReservedQuantity().Eval())
		if available < 0 || reserved < 0 {
			panic("Invalid inventory")
		}
		if available < qty {
			return result("OUT_OF_STOCK", nil)
		}
		re := commerce_platform.NewCommercePlatformExpression(root)
		if attempt == 0 {
			barrier(object{"pid": os.Getpid(), "session": token, "requestKey": key, "orderNumber": number, "quantity": qty, "rootVersion": required(re.Version().Eval()), "inventoryVersion": required(se.Version().Eval()), "available": available, "orderVersion": required(oe.Version().Eval())})
		}
		root.UpdateReservationSequence(required(re.ReservationSequence().Eval()) + 1)
		order.UpdateOrderStatusId(1002)
		stock.UpdateAvailableQuantity(available - qty)
		stock.UpdateReservedQuantity(reserved + qty)
		receipt := Q.StockReservations().Comment("Create immutable scoped reservation receipt").Purpose("Commit request idempotency with inventory").NewEntity(context)
		receipt.UpdateCommercePlatformId(required(re.Id().Eval()))
		receipt.UpdateCustomerOrderId(required(oe.Id().Eval()))
		receipt.UpdateInventoryId(required(se.Id().Eval()))
		receipt.UpdateRequestKey(key)
		receipt.UpdateBuyerReference(buyer)
		receipt.UpdateQuantity(qty)
		receipt.UpdateOrderNumber(number)
		receipt.UpdateSkuCode(sku)
		root.StockReservationList().Add(receipt)
		_, err = root.AuditAs(reserveReason).Save(context)
		if err != nil {
			if strings.Contains(err.Error(), "STOCK_RESERVATION_TEST_ABORT") {
				value := result("TRANSACTION_ABORTED", nil)
				value["reason"] = err.Error()
				return value
			}
			if !conflict(err) {
				panic(err)
			}
			reasons = append(reasons, err.Error())
			continue
		}
		saved, err := Q.StockReservations().WithCommercePlatformIs(required(re.Id().Eval())).WithBuyerReferenceIs(buyer).WithRequestKeyIs(key).Limit(2).Comment("Read committed reservation receipt").Purpose("Return durable idempotency identity").ExecuteForList(context)
		check(err)
		if len(saved.Data) != 1 {
			panic("Missing receipt")
		}
		return result("RESERVED", required(stock_reservation.NewStockReservationExpression(saved.Data[0]).Id().Eval()))
	}
	return result("CONFLICT_LIMIT", nil)
}
func seed(context *runtime.UserContext) {
	b, e := os.ReadFile(os.Getenv("ORDER_FIXTURE"))
	check(e)
	var f struct {
		Tenants []struct {
			Key       string
			Available int64
		}
		Buyers []string
		Orders []struct {
			Number   string
			Quantity int64
		}
		Sku              string
		ControlSku       string
		ControlAvailable int64
		UnitPriceMinor   int64
	}
	check(json.Unmarshal(b, &f))
	roots, e := Q.CommercePlatforms().Limit(2).Comment("Read initialized stock root").Purpose(seedReason).ExecuteForList(context)
	check(e)
	if len(roots.Data) != 1 {
		panic("Expected initialized root")
	}
	for n, t := range f.Tenants {
		root := roots.Data[0]
		if n != 0 {
			root = Q.CommercePlatforms().Comment("Create tenant").Purpose(seedReason).NewEntity(context)
		}
		root.UpdateName("Tenant " + t.Key[len(t.Key)-1:])
		root.UpdateTenantKey(t.Key)
		root.UpdateReservationSequence(0)
		_, e = root.AuditAs(seedReason).Save(context)
		check(e)
		rid := required(commerce_platform.NewCommercePlatformExpression(root).Id().Eval())
		for k := 0; k < 2; k++ {
			sku, qty := f.Sku, t.Available
			if k == 1 {
				sku, qty = f.ControlSku, f.ControlAvailable
			}
			stock := Q.Inventory().Comment("Create SKU inventory").Purpose(seedReason).NewEntity(context)
			stock.UpdateCommercePlatformId(rid)
			stock.UpdateSkuCode(sku)
			stock.UpdateAvailableQuantity(qty)
			stock.UpdateReservedQuantity(0)
			stock.UpdateWarehouseNote("Initial warehouse stock")
			_, e = stock.AuditAs(seedReason).Save(context)
			check(e)
		}
		for _, buyer := range f.Buyers {
			for _, d := range f.Orders {
				o := Q.CustomerOrders().Comment("Create stock Order").Purpose(seedReason).NewEntity(context)
				o.UpdateCommercePlatformId(rid)
				o.UpdateOrderStatusId(1001)
				o.UpdateOrderNumber(d.Number)
				o.UpdateBuyerReference(buyer)
				o.UpdateCurrencyCode("USD")
				o.UpdateTotalMinor(d.Quantity * f.UnitPriceMinor)
				note := "Stock reservation fixture order"
				o.UpdateOrderNote(note)
				_, e = o.AuditAs(seedReason).Save(context)
				check(e)
				i := Q.OrderItems().Comment("Create complete Order line").Purpose(seedReason).NewEntity(context)
				i.UpdateCustomerOrderId(required(customer_order.NewCustomerOrderExpression(o).Id().Eval()))
				i.UpdateSkuCode(f.Sku)
				i.UpdateProductName(f.Sku)
				i.UpdateQuantity(d.Quantity)
				i.UpdateUnitPriceMinor(f.UnitPriceMinor)
				i.UpdateLineTotalMinor(d.Quantity * f.UnitPriceMinor)
				_, e = i.AuditAs(seedReason).Save(context)
				check(e)
			}
		}
	}
}
func main() {
	phase := os.Args[1]
	context, e := ServiceRuntimeFromEnv()
	check(e)
	if phase == "bootstrap" || phase == "seed" {
		check(EnsureSchema(context))
	}
	switch phase {
	case "seed":
		seed(context)
	case "request", "worker":
		b, e := os.ReadFile(os.Getenv("ORDER_REQUEST"))
		check(e)
		var r object
		check(json.Unmarshal(b, &r))
		fmt.Println("ORDER_STOCK_BEGIN")
		value := handle(context, os.Getenv("ORDER_SESSION"), r)
		out, e := json.Marshal(value)
		check(e)
		fmt.Println("ORDER_STOCK_RESULT " + string(out))
	case "bootstrap":
	default:
		panic("Unknown phase")
	}
	fmt.Println("ORDER_OK phase=" + phase)
}
