// Package governance illustrates checks after authentication at a tool gateway.
package governance

import (
	"errors"
	"time"
)

type Scope struct {
	Workload, Tenant, Region, Tool, Action, Resource string
	KnowledgeSnapshot, PolicyVersion, GrantRef       string
	NotBefore, ExpiresAt                             time.Time
}

// Inputs must come from verified identity and server-side grant storage.
// A caller-supplied JSON object is not an authenticated grant.
type Request struct {
	Workload, Tenant, Region, Tool, Action, Resource string
	KnowledgeSnapshot                                string
}

func Authorize(now time.Time, grant Scope, req Request) error {
	if grant.GrantRef == "" || grant.PolicyVersion == "" ||
		!grant.ExpiresAt.After(grant.NotBefore) ||
		now.Before(grant.NotBefore) || !now.Before(grant.ExpiresAt) {
		return errors.New("invalid or inactive grant")
	}
	checks := [][2]string{
		{grant.Workload, req.Workload}, {grant.Tenant, req.Tenant},
		{grant.Region, req.Region}, {grant.Tool, req.Tool},
		{grant.Action, req.Action}, {grant.Resource, req.Resource},
		{grant.KnowledgeSnapshot, req.KnowledgeSnapshot},
	}
	for _, pair := range checks {
		if pair[0] == "" || pair[1] == "" || pair[0] != pair[1] {
			return errors.New("outside approved scope")
		}
	}
	return nil
}
