package governance

import (
	"errors"
	"sync"
)

// Budget is an in-memory, one-process illustration. Values are integer micro-USD.
// A production ledger needs durable transactions and an outbox, not this mutex.
type Budget struct {
	mu                 sync.Mutex
	limit, spent, held int64
	reservations       map[string]int64
	settled            map[string]int64
}

func NewBudget(limit int64) (*Budget, error) {
	if limit < 0 {
		return nil, errors.New("negative budget")
	}
	return &Budget{limit: limit, reservations: map[string]int64{}, settled: map[string]int64{}}, nil
}

// Reserve is idempotent for the same operation ID and amount.
func (b *Budget) Reserve(id string, maximum int64) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	if id == "" || maximum <= 0 {
		return errors.New("invalid reservation")
	}
	if _, ok := b.settled[id]; ok {
		return errors.New("already settled")
	}
	if prior, ok := b.reservations[id]; ok {
		if prior == maximum {
			return nil
		}
		return errors.New("reservation conflict")
	}
	if maximum > b.limit-b.spent-b.held {
		return errors.New("budget exhausted")
	}
	b.reservations[id] = maximum
	b.held += maximum
	return nil
}

// Settle requires a verified final charge within the reserved upper bound.
// Unknown provider outcomes must remain held pending reconciliation.
func (b *Budget) Settle(id string, actual int64) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	if prior, ok := b.settled[id]; ok {
		if actual == prior {
			return nil
		}
		return errors.New("settlement conflict")
	}
	maximum, ok := b.reservations[id]
	if !ok || actual < 0 || actual > maximum {
		return errors.New("invalid settlement: reconcile")
	}
	b.held -= maximum
	b.spent += actual
	delete(b.reservations, id)
	b.settled[id] = actual
	return nil
}
