package dto

import (
	"time"
)

// AppDefinitionResponse is the browser-facing app catalog item.
type AppDefinitionResponse struct {
	ID                 string                                   `json:"id"`
	Slug               string                                   `json:"slug"`
	Name               string                                   `json:"name"`
	Description        string                                   `json:"description"`
	AvatarURL          string                                   `json:"avatarUrl"`
	Kind               string                                   `json:"kind"`
	Visibility         string                                   `json:"visibility"`
	CatalogVisibility  string                                   `json:"catalogVisibility,omitempty"`
	RuntimeCapability  *AppRuntimeCapabilityResponse            `json:"runtimeCapability,omitempty"`
	ProviderConnection *AppProviderConnectionCapabilityResponse `json:"providerConnection,omitempty"`
	CreatedAt          time.Time                                `json:"createdAt"`
	UpdatedAt          time.Time                                `json:"updatedAt"`
}

// AppRuntimeCapabilityResponse is the minimal non-secret runtime metadata needed
// to render installed external App setup.
type AppRuntimeCapabilityResponse struct {
	Supported  bool     `json:"supported"`
	Transports []string `json:"transports"`
}

// AppProviderConnectionCapabilityResponse exposes only the trusted Extension
// domain needed to discover the generic connection form.
type AppProviderConnectionCapabilityResponse struct {
	Domain string `json:"domain"`
}

// AppConnectionResponse is the browser-facing app connection shape.
type AppConnectionResponse struct {
	ID                 string    `json:"id"`
	ExternalSubjectRef string    `json:"externalSubjectRef"`
	DisplayLabel       string    `json:"displayLabel"`
	RequiresUpgrade    bool      `json:"requiresUpgrade,omitempty"`
	MissingPermissions []string  `json:"missingPermissions,omitempty"`
	MissingEvents      []string  `json:"missingEvents,omitempty"`
	Enabled            bool      `json:"enabled"`
	CreatedAt          time.Time `json:"createdAt"`
	UpdatedAt          time.Time `json:"updatedAt"`
}

// AppInstallationResponse is the browser-facing app installation shape.
type AppInstallationResponse struct {
	ID                 string                                   `json:"id"`
	AppID              string                                   `json:"appId"`
	AppSlug            string                                   `json:"appSlug"`
	AppName            string                                   `json:"appName"`
	AvatarURL          string                                   `json:"avatarUrl"`
	InstanceKey        string                                   `json:"instanceKey,omitempty"`
	OwnershipKind      string                                   `json:"ownershipKind,omitempty"`
	MemberID           string                                   `json:"memberId"`
	Handle             string                                   `json:"handle"`
	Connections        []AppConnectionResponse                  `json:"connections"`
	RuntimeCapability  *AppRuntimeCapabilityResponse            `json:"runtimeCapability,omitempty"`
	ProviderConnection *AppProviderConnectionCapabilityResponse `json:"providerConnection,omitempty"`
	CatalogVisibility  string                                   `json:"catalogVisibility,omitempty"`
	CanManageApp       bool                                     `json:"canManageApp"`
	Config             map[string]any                           `json:"config,omitempty"`
	Enabled            bool                                     `json:"enabled"`
	CreatedAt          time.Time                                `json:"createdAt"`
	UpdatedAt          time.Time                                `json:"updatedAt"`
	InChannel          *bool                                    `json:"inChannel,omitempty"`
}

type AppInstallationChannelResponse struct {
	ID          string `json:"id"`
	Slug        string `json:"slug"`
	DisplayName string `json:"displayName"`
	Description string `json:"description"`
	Visibility  string `json:"visibility"`
	CanRemove   bool   `json:"canRemove"`
}

// InstallationExtensionDefinitionResponse is immutable, secret-free Library
// identity/display metadata allowed by one App Definition.
type InstallationExtensionDefinitionResponse struct {
	Domain         string `json:"domain"`
	Version        int    `json:"version"`
	Digest         string `json:"digest"`
	DisplayName    string `json:"displayName"`
	DefaultName    string `json:"defaultName,omitempty"`
	DefaultEnabled bool   `json:"defaultEnabled"`
}

// InstallationExtensionResponse is the App settings projection for one
// allowed Extension and its optional Workspace selection.
type InstallationExtensionResponse struct {
	ID              string                                  `json:"id,omitempty"`
	ExtensionName   string                                  `json:"extensionName,omitempty"`
	Definition      InstallationExtensionDefinitionResponse `json:"definition"`
	Selected        bool                                    `json:"selected"`
	Status          string                                  `json:"status,omitempty"`
	DisabledReason  string                                  `json:"disabledReason,omitempty"`
	SelectionSource string                                  `json:"selectionSource,omitempty"`
	CreatedAt       *time.Time                              `json:"createdAt,omitempty"`
	UpdatedAt       *time.Time                              `json:"updatedAt,omitempty"`
}

// SearchEngineConnectionConfigResponse contains only non-secret provider
// configuration.
type SearchEngineConnectionConfigResponse struct {
	BaseURL  string `json:"baseUrl,omitempty"`
	Language string `json:"language,omitempty"`
}

// SearchEngineConnectionCredentialsResponse exposes configured state without
// returning write-only credential values.
type SearchEngineConnectionCredentialsResponse struct {
	APIKeyConfigured bool `json:"apiKeyConfigured"`
}

// SearchEngineConnectionResponse is the browser-facing search App connection.
type SearchEngineConnectionResponse struct {
	Provider    string                                    `json:"provider"`
	Active      bool                                      `json:"active"`
	Config      SearchEngineConnectionConfigResponse      `json:"config"`
	Credentials SearchEngineConnectionCredentialsResponse `json:"credentials"`
	UpdatedAt   *time.Time                                `json:"updatedAt,omitempty"`
}

// SearchEngineConnectionTestResponse acknowledges a successful bounded probe.
type SearchEngineConnectionTestResponse struct {
	OK bool `json:"ok"`
}

// AppVisibilityUpdateResponse acknowledges only the canonical audience. The
// removed channel identities remain server-internal because a App manager is
// not necessarily authorized to discover every private channel containing it.
type AppVisibilityUpdateResponse struct {
	CatalogVisibility string `json:"catalogVisibility"`
}

// WorkspaceAppPermissionsResponse exposes only the effective permission scopes
// of one active external App. AllowedScopes is the immutable ceiling pinned by
// the manifest; ActiveScopes is the currently granted narrowed subset;
// PolicyDigest is the optimistic-concurrency token for PATCH.
type WorkspaceAppPermissionsResponse struct {
	AllowedScopes []string `json:"allowedScopes"`
	ActiveScopes  []string `json:"activeScopes"`
	PolicyDigest  string   `json:"policyDigest"`
}

// DirectAppInstallationResponse is returned by privileged App mutations. The
// resulting config is part of the command acknowledgement and therefore must
// remain present even when it is empty. Read/list responses intentionally keep
// AppInstallationResponse.Config optional for backwards compatibility.
type DirectAppInstallationResponse struct {
	AppInstallationResponse
	Config map[string]any `json:"config"`
}

// InstallationAccessGrantResponse is the browser-facing ACL row of one App
// installation. Scopes are the granted capability subset; AccessRole is
// use or manage.
type InstallationAccessGrantResponse struct {
	ID            string    `json:"id"`
	PrincipalKind string    `json:"principalKind"`
	PrincipalRef  string    `json:"principalRef"`
	AccessRole    string    `json:"accessRole"`
	Status        string    `json:"status"`
	Scopes        []string  `json:"scopes"`
	CreatedAt     time.Time `json:"createdAt"`
	UpdatedAt     time.Time `json:"updatedAt"`
}

// InstallationShareRequestResponse is the browser-facing share approval
// request. ReviewedPolicy is the exact capability snapshot the approver is
// deciding on; it never contains credentials.
type InstallationShareRequestResponse struct {
	ID             string                           `json:"id"`
	AppID          string                           `json:"appId"`
	AppName        string                           `json:"appName"`
	InstallationID string                           `json:"installationId"`
	RequestKind    string                           `json:"requestKind"`
	Status         string                           `json:"status"`
	Reason         string                           `json:"reason"`
	ReviewedPolicy *InstallationSharePolicyResponse `json:"reviewedPolicy,omitempty"`
	CreatedAt      time.Time                        `json:"createdAt"`
	UpdatedAt      time.Time                        `json:"updatedAt"`
	DecidedAt      *time.Time                       `json:"decidedAt,omitempty"`
}

// InstallationSharePolicyResponse is the reviewed policy snapshot pinned by a
// share request: active scopes, installation config, connection identities,
// and the actual Extension selections.
type InstallationSharePolicyResponse struct {
	DefinitionID       string           `json:"definitionId"`
	Version            string           `json:"version"`
	Scopes             []string         `json:"scopes"`
	PolicyDigest       string           `json:"policyDigest"`
	InstallationConfig map[string]any   `json:"installationConfig"`
	Connections        []map[string]any `json:"connections"`
	Extensions         []map[string]any `json:"extensions"`
}

// AppInstallationRequestResponse is the browser-facing app installation request shape.
type AppInstallationRequestResponse struct {
	ID          string `json:"id"`
	RequestKind string `json:"requestKind"`
	Status      string `json:"status"`
}

// PendingAppInstallationRequestResponse is the requester-scoped read model.
// It includes only identifiers needed to associate a pending proposal with an
// App detail route; request configuration and reviewer data stay server-side.
type PendingAppInstallationRequestResponse struct {
	ID             string    `json:"id"`
	AppID          string    `json:"appId"`
	AppSlug        string    `json:"appSlug"`
	AppName        string    `json:"appName,omitempty"`
	RequestKind    string    `json:"requestKind"`
	Status         string    `json:"status"`
	Reason         string    `json:"reason,omitempty"`
	InstallationID string    `json:"installationId,omitempty"`
	CreatedAt      time.Time `json:"createdAt"`
	// ReviewedPolicy carries a share request's pinned capability snapshot
	// so workspace admins can review exactly what approval would grant.
	ReviewedPolicy *InstallationSharePolicyResponse `json:"reviewedPolicy,omitempty"`
}

// CustomAppRequestResponse is the secret-free acknowledgement returned
// by the narrow external App onboarding request endpoint. Initial runtime
// credentials do not exist until the approved requester claims them later.
type CustomAppRequestResponse struct {
	ID          string `json:"id"`
	RequestKind string `json:"requestKind"`
	Status      string `json:"status"`
}

// CustomAppInstallationResponse is the admin-only direct onboarding response. The
// nested installation is durable; callbackSigningSecret and runnerToken are
// one-time values and are absent from ordinary installation reads.
type CustomAppInstallationResponse struct {
	Installation          DirectAppInstallationResponse `json:"installation"`
	CallbackSigningSecret string                        `json:"callbackSigningSecret,omitempty"`
	RunnerToken           string                        `json:"runnerToken,omitempty"`
}

// AppManagerResponse is the minimal versioned assignment shape required by
// the workspace App administrator UI.
type AppManagerResponse struct {
	ID       string `json:"id"`
	MemberID string `json:"memberId"`
	Status   string `json:"status"`
	Version  int64  `json:"version"`
}

// AppAvatarResponse acknowledges the canonical avatar applied across the App
// definition and service-actor projections.
type AppAvatarResponse struct {
	AvatarURL string `json:"avatarUrl"`
}

// MatchedWebhookSubscriptionResponse is the nested shape for webhook delivery matched subscriptions.
type MatchedWebhookSubscriptionResponse struct {
	ID                 string `json:"id"`
	ThreadID           string `json:"threadId"`
	ResourceIdentifier string `json:"resourceIdentifier"`
}

// AppWebhookDeliveryResponse is the browser-facing webhook delivery shape.
type AppWebhookDeliveryResponse struct {
	ID                   string                               `json:"id"`
	InstallationID       string                               `json:"installationId"`
	AppID                string                               `json:"appId"`
	AppSlug              string                               `json:"appSlug"`
	AppName              string                               `json:"appName"`
	DeliveryKey          string                               `json:"deliveryKey"`
	EventType            string                               `json:"eventType"`
	PayloadExcerpt       string                               `json:"payloadExcerpt"`
	MatchedSubscriptions []MatchedWebhookSubscriptionResponse `json:"matchedSubscriptions"`
	Outcome              string                               `json:"outcome"`
	ProcessedAt          *time.Time                           `json:"processedAt,omitempty"`
	ErrorMessage         string                               `json:"errorMessage,omitempty"`
	CreatedAt            time.Time                            `json:"createdAt"`
	UpdatedAt            time.Time                            `json:"updatedAt"`
}

// AgentAppAuthorizationResponse is the browser-facing agent/app authorization shape.
type AgentAppAuthorizationResponse struct {
	AppID                string     `json:"appId"`
	AppSlug              string     `json:"appSlug"`
	AppName              string     `json:"appName"`
	AvatarURL            string     `json:"avatarUrl"`
	AppInstallationID    string     `json:"appInstallationId"`
	AppMemberID          string     `json:"appMemberId"`
	Handle               string     `json:"handle"`
	InstallationEnabled  bool       `json:"installationEnabled"`
	Supported            bool       `json:"supported"`
	MCPName              string     `json:"mcpName"`
	MCPTools             []string   `json:"mcpTools"`
	Scopes               []string   `json:"scopes"`
	AuthorizationID      string     `json:"authorizationId,omitempty"`
	AuthorizationStatus  string     `json:"authorizationStatus"`
	DisabledReason       string     `json:"disabledReason,omitempty"`
	AuthorizedByMemberID string     `json:"authorizedByMemberId,omitempty"`
	PolicyVersion        int64      `json:"policyVersion,omitempty"`
	AuthorizedAt         *time.Time `json:"authorizedAt,omitempty"`
	UpdatedAt            *time.Time `json:"updatedAt,omitempty"`
}

// ServiceEventSubscriptionResponse is the browser-facing service-event subscription shape.
type ServiceEventSubscriptionResponse struct {
	ID                     string         `json:"id"`
	AppInstallationID      string         `json:"appInstallationId"`
	AppBindingID           string         `json:"appBindingId"`
	ProviderConnectionRef  string         `json:"providerConnectionRef,omitempty"`
	Provider               string         `json:"provider"`
	TargetKind             string         `json:"targetKind"`
	TargetRef              string         `json:"targetRef"`
	DeliveryScopeID        string         `json:"deliveryScopeId"`
	PermissionCheckScopeID string         `json:"permissionCheckScopeId"`
	ResourceKind           string         `json:"resourceKind"`
	ResourceRef            string         `json:"resourceRef"`
	ResourceKey            string         `json:"resourceKey"`
	EventFilters           map[string]any `json:"eventFilters"`
	Status                 string         `json:"status"`
	PausedReason           string         `json:"pausedReason,omitempty"`
	CreatedByMemberID      string         `json:"createdByMemberId"`
	CreatedByActorType     string         `json:"createdByActorType"`
	CreatedByActorID       string         `json:"createdByActorId"`
	AuthorizerUserID       string         `json:"authorizerUserId,omitempty"`
	DeliveryPolicy         string         `json:"deliveryPolicy"`
	NotifyPrincipal        bool           `json:"notifyPrincipal"`
	CreatedVia             string         `json:"createdVia"`
	TriggerID              string         `json:"triggerId"`
	Kind                   string         `json:"kind"`
	OwnerKind              string         `json:"ownerKind"`
	SourceType             string         `json:"sourceType"`
	CorrelationID          string         `json:"correlationId,omitempty"`
	LastEventAt            *time.Time     `json:"lastEventAt,omitempty"`
	LastFailureAt          *time.Time     `json:"lastFailureAt,omitempty"`
	LastFailureCode        string         `json:"lastFailureCode,omitempty"`
	LastFailureMessage     string         `json:"lastFailureMessage,omitempty"`
	CreatedAt              time.Time      `json:"createdAt"`
	UpdatedAt              time.Time      `json:"updatedAt"`
	PausedAt               *time.Time     `json:"pausedAt,omitempty"`
	RemovedAt              *time.Time     `json:"removedAt,omitempty"`
}

// ServiceEventSubscriptionActionResultResponse is returned by service-event subscription create/pause/resume/delete.
type ServiceEventSubscriptionActionResultResponse struct {
	Status        string                           `json:"status"`
	AlreadyExists bool                             `json:"alreadyExists"`
	Subscription  ServiceEventSubscriptionResponse `json:"subscription"`
	BindingID     string                           `json:"bindingId"`
	Message       string                           `json:"message"`
}

// ProviderWatchResponse is a legacy browser compatibility alias.
type ProviderWatchResponse = ServiceEventSubscriptionResponse

// ProviderWatchActionResultResponse is a legacy browser compatibility shape.
type ProviderWatchActionResultResponse struct {
	Status        string                `json:"status"`
	AlreadyExists bool                  `json:"alreadyExists"`
	Watch         ProviderWatchResponse `json:"watch"`
	BindingID     string                `json:"bindingId"`
	Message       string                `json:"message"`
}

// ExtensionProviderCredentialFieldResponse describes one declared provider
// credential field for the connect form.
type ExtensionProviderCredentialFieldResponse struct {
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`
	Description string `json:"description"`
	Required    bool   `json:"required"`
	Secret      bool   `json:"secret"`
	// Configured reports whether this field has a stored value. It is a
	// presence flag only — secret values are never returned.
	Configured bool `json:"configured"`
}

// ExtensionProviderConnectionResponse is the secret-free browser-facing
// provider connection state.
type ExtensionProviderConnectionResponse struct {
	Slug          string                                     `json:"slug"`
	Active        bool                                       `json:"active"`
	CredentialSet bool                                       `json:"credentialSet"`
	UpdatedAt     *time.Time                                 `json:"updatedAt,omitempty"`
	Values        map[string]string                          `json:"values,omitempty"`
	Fields        []ExtensionProviderCredentialFieldResponse `json:"fields"`
}

// ExtensionProviderConnectionTestResponse reports a live credential check.
type ExtensionProviderConnectionTestResponse struct {
	OK bool `json:"ok"`
}
