import {type CurrentUser} from '@sanity/types'

import {type AccessResourceType} from '../../access/checkPermissions'
import {type Application, type ApplicationInclude} from '../../applications/applications'
import {type Installation, type InstallationInclude} from '../../installations/installations'
import {type OrganizationBase} from '../../organization/organization'

/**
 * Identifies a module federation expose and the manifest that serves it.
 * @public
 * @category Remote Modules
 */
export interface RemoteModuleRef {
  readonly entry: string
  readonly moduleId: string
  readonly version: string
}

/**
 * Application types that can receive configuration modules.
 *
 * The dashboard supplies this value over the message bus, so any string is accepted; known
 * types are listed for autocomplete. `& {}` keeps the literal from collapsing into `string`.
 * @public
 * @category Types
 * @category Message Bus
 */
export type ApplicationConfigAppType = 'media-library' | (string & {})

/**
 * Identifies a configuration module for an application or application type.
 * @public
 * @category Types
 * @category Message Bus
 */
export interface ApplicationConfig extends RemoteModuleRef {
  readonly appId?: Application['id']
  readonly appType: ApplicationConfigAppType
}

/**
 * The capabilities a host can provide.
 *
 * Reuses the Studio's rendering-context identifiers so an application can hide its own
 * implementation of anything the host provides.
 * @public
 * @category Message Bus
 */
export const capabilities = ['globalUserMenu', 'favorites', 'history'] as const

/**
 * A capability a host can provide.
 * @public
 * @category Message Bus
 */
export type Capability = (typeof capabilities)[number]

/**
 * The capabilities the host provides. A missing key means the host does not provide it.
 * @public
 * @category Message Bus
 */
export type CapabilityRecord = Partial<Record<Capability, boolean>>

/**
 * A document a user viewed, edited, created, or deleted in an application.
 * @public
 * @category Types
 * @category Message Bus
 */
export interface DocumentActivity {
  readonly kind: 'document'
  readonly eventType: 'viewed' | 'edited' | 'created' | 'deleted'
  readonly document: {
    readonly id: string
    readonly type: string
    readonly resource: {
      readonly id: string
      readonly type: 'dataset' | 'media-library' | 'canvas'
      /** Schema collection the document belongs to; the workspace name for studios. */
      readonly schemaName?: string
    }
  }
}

/**
 * Activity an application reports to the host. Discriminated on `kind`.
 * @public
 * @category Types
 * @category Message Bus
 */
export type ApplicationActivity = DocumentActivity

/**
 * A document a user favorited, addressed like {@link DocumentActivity}'s document.
 * @public
 * @category Types
 * @category Message Bus
 */
export type FavoriteDocument = DocumentActivity['document']

/**
 * A label rendered for an application interface; `null` clears it.
 * @internal
 */
export type ApplicationStatus = {label: string | null}

/**
 * Updates the status rendered for an application interface.
 * @internal
 */
export type ApplicationStatusUpdate = {
  /** The application interface name. */
  name: string
  /** The status to render. */
  value: ApplicationStatus
}

/**
 * What an application is currently showing: the Comlink agent resource context, made generic.
 * @public
 * @category Types
 * @category Message Bus
 */
export interface ApplicationContext {
  /** The resource the application is working in. Types follow `@sanity/client`'s resource config. */
  readonly resource: {
    readonly id: string
    readonly type: 'dataset' | 'media-library' | 'canvas'
  }
  /** The open document, or `null` when none is open. */
  readonly document: {readonly id: string} | null
}

/**
 * An application served by a CLI dev server. The workbench publishes it in the same shape as a
 * deployed application; `local` marks it and names the dev server it is served from.
 * @public
 * @category Types
 * @category Message Bus
 */
export type LocalApplication = Application<ApplicationInclude> & {
  readonly local: {readonly host: string; readonly port: number}
}

/**
 * Declares a topic that stores and replays its current value.
 * @public
 * @category Message Bus
 */
export type StateTopicDef<T> = {kind: 'state'; value: T}

/**
 * Declares a topic that delivers events and an optional reply.
 * @public
 * @category Message Bus
 */
export type EventTopicDef<P, R = never> = {
  kind: 'event'
  payload: P
  reply?: R
}

/**
 * Represents a successful topic value or a failed topic operation.
 * @public
 * @category Message Bus
 */
export type TopicResult<T> = {ok: true; value: T} | {ok: false}

/**
 * Identifies a dashboard application and a route within it.
 * @public
 * @category Types
 * @category Message Bus
 */
export type NavigationTarget = {
  /** The application ID, or `null` for dashboard-level routes. */
  appId: Application['id'] | null
  /** The route path, including its query string and fragment. */
  path: string
}

/**
 * Describes the current dashboard location and an active navigation.
 * @public
 * @category Types
 * @category Message Bus
 */
export type NavigationLocation = NavigationTarget & {
  /** The active navigation, or `null` when navigation is idle. */
  transition: {
    /** Whether the navigation pushes or replaces browser history. */
    navigationType: 'push' | 'replace'
    /** The requested destination. */
    to: NavigationTarget
  } | null
}

/**
 * Declares the topics provided by the dashboard.
 * @public
 * @category Message Bus
 */
export interface DashboardTopics {
  /**
   * Asks the dashboard to show its access request prompt for a resource the user can't access,
   * scoped like the Access API's `/access/{resourceType}/{resourceId}/requests`. Replies once the
   * prompt is shown. The prompt handles the Access API outcome (SSO enforcement, pending or
   * declined requests, request limits), so the reply doesn't report it.
   *
   * `ok: false` reasons:
   * - `unsupported`: the dashboard doesn't show access requests for the sending application
   * - `already-has-access`: the user already has access to the resource, so there is nothing to request
   */
  'access.request': EventTopicDef<
    {resourceType: Extract<AccessResourceType, 'organization' | 'project'>; resourceId: string},
    {ok: true} | {ok: false; reason: 'unsupported' | 'already-has-access'}
  >
  /** Reports user activity in an application, e.g. for the recents feed. Fire-and-forget. */
  'applications.activity': EventTopicDef<ApplicationActivity>
  /**
   * The base path for an application.
   *
   * An unknown application returns `{ok: false}`.
   */
  'applications.base-path': StateTopicDef<TopicResult<string>>
  /** The capabilities the host provides. A missing key means the host does not provide it. */
  'applications.capabilities': StateTopicDef<CapabilityRecord>
  /** The available application configuration modules. */
  'applications.config': StateTopicDef<ApplicationConfig[] | null>
  /** The foreground application's context, or `null` when it has published none. */
  'applications.context': StateTopicDef<
    (ApplicationContext & {readonly appId: Application['id']}) | null
  >
  /** Publishes the sending application's context. `null` clears it. Fire-and-forget. */
  'applications.context.update': EventTopicDef<ApplicationContext | null>
  /** The foreground application ID, or `null` on dashboard-level routes. */
  'applications.foreground': StateTopicDef<Application['id'] | null>
  /**
   * The dashboard applications and installations available to the current user. Each member
   * publishes its own raw serialised record, so the kinds are distinguished by shape: an
   * {@link Application} has a `type` of `'studio' | 'coreApp'`, a {@link LocalApplication} adds
   * `local`, and an {@link Installation} has no `type` and carries `applicationId` with a nested
   * `application` object.
   */
  'applications.list': StateTopicDef<TopicResult<
    (Application<ApplicationInclude> | LocalApplication | Installation<InstallationInclude>)[]
  > | null>
  'applications.status.update': EventTopicDef<ApplicationStatusUpdate>
  /**
   * The session token for the reading connection, or `null` while signed out. The host
   * writes it to each connection separately, so one application never sees another's token.
   */
  'auth.token': StateTopicDef<string | null>
  /** Requests a dashboard session token. */
  'auth.token.refresh': EventTopicDef<void, string>
  /** The signed-in user's favorited documents, published while the host provides `favorites`. */
  'favorites.documents': StateTopicDef<FavoriteDocument[]>
  /**
   * Favorites or unfavorites a document. The host replies once `favorites.documents` reflects
   * the change, so a read after the reply sees it. A favorite is identified by its published
   * document ID, type, resource and `schemaName` (workspace).
   */
  'favorites.update': EventTopicDef<{document: FavoriteDocument; favorited: boolean}, void>
  /** The current dashboard location and active navigation. */
  'navigation.location': StateTopicDef<NavigationLocation | null>
  /**
   * Requests navigation and replies when the location commits.
   *
   * `ok: false` reasons:
   * - `not-navigable`: the URL cannot be handled by a dashboard application
   * - `interrupted`: another navigation superseded the request
   * - `failed`: the router rejected or did not commit the request
   */
  'navigation.location.update': EventTopicDef<
    {
      url: string
      history?: 'push' | 'replace'
    },
    {ok: true} | {ok: false; reason: 'not-navigable' | 'interrupted' | 'failed'}
  >
  /** The current organization, or `null` without an active organization. */
  'organizations.current': StateTopicDef<Pick<OrganizationBase, 'id' | 'name' | 'slug'> | null>
  /** The open panel, its application, display mode, and optional width in pixels. */
  'panels.mode': StateTopicDef<TopicResult<
    | {appId: string; name: string; mode: 'aside'; size?: number}
    | {appId: string; name: string; mode: 'full'}
    | null
  > | null>
  /** Opens, updates, resizes, or closes an application's panel. */
  'panels.mode.set': EventTopicDef<
    {name: string; mode: 'aside' | 'full'} | {name: string; size: number} | null
  >
  /** The resolved dashboard color scheme. */
  'preferences.color-scheme': StateTopicDef<'light' | 'dark'>
  /** Whether the dashboard dock is pinned open. */
  'preferences.dock-locked': StateTopicDef<boolean>
  /** The signed-in user, or `null` while signed out. */
  'users.current': StateTopicDef<CurrentUser | null>
}

/**
 * Declares every topic available through the message bus.
 * @public
 * @category Message Bus
 */
// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Declaration merging extends the SDK manifest.
export interface Topics extends DashboardTopics {}

/**
 * Hides provisional topics from the public message bus methods.
 * @internal
 */
export type MessageBusTopics = Omit<Topics, 'applications.status.update'>

/**
 * Every declared topic name.
 * @public
 * @category Message Bus
 */
export type TopicName<TTopics = Topics> = keyof TTopics

type StateTopicsOf<T> = {
  [K in keyof T]: T[K] extends {kind: 'state'} ? K : never
}[keyof T]

/**
 * Names of state topics exposed by message bus methods.
 * @public
 * @category Message Bus
 */
export type StateTopic<TTopics = MessageBusTopics> = StateTopicsOf<TTopics>

type TopicOwnership = {readonly type: 'same_app'} | {readonly type: 'any_app'}

// State is only ever written by the host, one connection at a time, so it carries no ownership.
type TopicManifestEntry<T> = T extends {kind: 'state'; value: infer V}
  ? {readonly kind: 'state'; readonly seed: V | undefined}
  : {readonly kind: 'event'; readonly ownership: TopicOwnership}

// The value a connection's copy of the topic starts with; `undefined` means unpublished.
const stateTopic = <const V>(seed: V) => ({kind: 'state', seed}) as const

// `same_app` restricts responding to the application that installed the bus.
const dashboardEvent = {kind: 'event', ownership: {type: 'same_app'}} as const

type DashboardTopicManifest = {
  readonly [K in keyof DashboardTopics]: TopicManifestEntry<DashboardTopics[K]>
}

/**
 * Defines the runtime kind, ownership, and initial value of dashboard topics.
 * @internal
 */
export const DASHBOARD_TOPIC_MANIFEST: DashboardTopicManifest = {
  'access.request': dashboardEvent,
  'applications.activity': dashboardEvent,
  'applications.base-path': stateTopic(undefined),
  'applications.capabilities': stateTopic(undefined),
  'applications.config': stateTopic(undefined),
  'applications.context': stateTopic(undefined),
  'applications.context.update': dashboardEvent,
  'applications.foreground': stateTopic(undefined),
  'applications.list': stateTopic(undefined),
  'applications.status.update': dashboardEvent,
  'auth.token': stateTopic(undefined),
  'auth.token.refresh': dashboardEvent,
  'favorites.documents': stateTopic(undefined),
  'favorites.update': dashboardEvent,
  'navigation.location': stateTopic(undefined),
  'navigation.location.update': dashboardEvent,
  'organizations.current': stateTopic(undefined),
  'panels.mode': stateTopic({ok: true, value: null}),
  'panels.mode.set': dashboardEvent,
  'preferences.color-scheme': stateTopic(undefined),
  'preferences.dock-locked': stateTopic(undefined),
  'users.current': stateTopic(undefined),
}

/**
 * Defines the runtime manifest accepted from any message bus version.
 * @internal
 */
export type TopicManifest = Readonly<
  Record<
    string,
    | {readonly kind: 'state'; readonly seed: unknown}
    | {readonly kind: 'event'; readonly ownership: TopicOwnership}
  >
>

/**
 * Names of event topics exposed by message bus methods.
 * @public
 * @category Message Bus
 */
export type EventTopic<TTopics = MessageBusTopics> = {
  [K in keyof TTopics]: TTopics[K] extends {kind: 'event'} ? K : never
}[keyof TTopics]

/**
 * The value type of a state topic.
 * @public
 * @category Message Bus
 */
export type ValueOf<K extends StateTopic<TTopics>, TTopics = Topics> =
  TTopics[K] extends StateTopicDef<infer T> ? T : never

/**
 * The payload type of an event topic.
 * @public
 * @category Message Bus
 */
export type PayloadOf<K extends EventTopic<TTopics>, TTopics = Topics> =
  TTopics[K] extends EventTopicDef<infer P, infer _R> ? P : never

/**
 * The reply type of an event topic (`never` if it declares none).
 * @public
 * @category Message Bus
 */
export type ReplyOf<K extends EventTopic<TTopics>, TTopics = Topics> =
  TTopics[K] extends EventTopicDef<infer _P, infer R> ? R : never

/**
 * Converts a topic value between 2 adjacent versions.
 * @internal
 */
export interface TopicMigration {
  /** The older version. */
  readonly from: number
  /** The newer version. */
  readonly to: number
  /** Converts an older state value or event payload to the newer version. */
  up(older: unknown): unknown
  /** Converts a newer state value or event payload to the older version. */
  down(newer: unknown): unknown
  /** Converts event replies between these versions. */
  readonly reply?: {
    /** Converts an older reply to the newer version. */
    up(older: unknown): unknown
    /** Converts a newer reply to the older version. */
    down(newer: unknown): unknown
  }
}

/**
 * Defines the bundled migration chain for each topic.
 * @internal
 */
export const topicMigrations: Partial<Record<TopicName, readonly TopicMigration[]>> = {}
