package quota

import (
	"fmt"
	"strings"
)

type PlanKey string
type MetricKey string
type Scope string

const (
	PlanFree PlanKey = "free"

	MetricWorkspaces        MetricKey = "workspaces"
	MetricSeats             MetricKey = "seats"
	MetricMachines          MetricKey = "machines"
	MetricAgents            MetricKey = "agents"
	MetricChannels          MetricKey = "channels"
	MetricManagedMemories   MetricKey = "managed_memories"
	MetricSkillRepositories MetricKey = "skill_repositories"

	ScopeOrganization    Scope = "organization"
	ScopeAgentOwner      Scope = "agent_owner"
	ScopeWorkspaceMember Scope = "workspace_member"
	ScopeWorkspace       Scope = "workspace"

	ErrorCodeQuotaExceeded = "quota_exceeded"
)

type ExceededError struct {
	OrganizationID string
	PlanKey        PlanKey
	PlanName       string
	Metric         MetricKey
	Limit          int64
	Current        int64
	Delta          int64
	Scope          Scope
}

func (err ExceededError) Error() string {
	metric := strings.TrimSpace(string(err.Metric))
	if metric == "" {
		metric = "resource"
	}
	planKey := strings.TrimSpace(string(err.PlanKey))
	if planKey == "" {
		planKey = "unknown"
	}
	planName := strings.TrimSpace(err.PlanName)
	if planName == "" {
		planName = planKey
	}
	switch err.Scope {
	case ScopeAgentOwner:
		return fmt.Sprintf("organization %s plan allows each human owner up to %d %s; current owner usage is %d and this request needs %d more", planName, err.Limit, metric, err.Current, err.Delta)
	case ScopeWorkspaceMember:
		return fmt.Sprintf("organization %s plan allows each workspace member up to %d %s; current workspace member usage is %d and this request needs %d more", planName, err.Limit, metric, err.Current, err.Delta)
	case ScopeWorkspace:
		return fmt.Sprintf("organization %s plan allows each workspace up to %d %s; current workspace usage is %d and this request needs %d more", planName, err.Limit, metric, err.Current, err.Delta)
	default:
		return fmt.Sprintf("organization %s plan allows up to %d %s; current usage is %d and this request needs %d more", planName, err.Limit, metric, err.Current, err.Delta)
	}
}

func (err ExceededError) Code() string {
	return ErrorCodeQuotaExceeded
}
