/**
 * OAuth scope vocabulary → ApiScope mapping — zapier-make-integration (wave-13).
 *
 * The spec-177 OAuth grant uses `read:resource` / `write:resource` vocabulary.
 * The tenant-public-api auth middleware uses `resource:read` / `resource:write`.
 * This module bridges the two so that OAuth bearer tokens authorize `/v1/*` calls.
 */
import type { ApiScope } from './scopes'

/**
 * Maps spec-177 OAuth scope strings to public-API ApiScope values.
 * Space-split the `scope` field from `oauth_access_tokens` and map each token
 * through this table before calling `hasScope(mappedScopes, required)`.
 *
 * Keys that are missing from this map are silently dropped (unknown scopes
 * grant nothing).
 */
export const OAUTH_SCOPE_TO_API_SCOPE: Record<string, ApiScope> = {
  'read:invoices':   'invoices:read',
  'write:invoices':  'invoices:write',
  'read:customers':  'customers:read',
  'write:customers': 'customers:write',
  'read:leads':      'leads:read',
  'write:leads':     'leads:write',
  'read:time':       'time:read',
  'write:time':      'time:write',
  'read:events':     'events:read',
  'read:tasks':      'tasks:read',
  'write:tasks':     'tasks:write',
  'read:projects':   'projects:read',
  'read:expenses':   'expenses:read',
}

/**
 * Convert a space-separated OAuth scope string into an array of ApiScope values.
 * Unknown scope tokens are dropped.
 */
export function mapOAuthScopesToApiScopes(oauthScope: string): ApiScope[] {
  return oauthScope
    .split(' ')
    .filter(Boolean)
    .flatMap((s) => {
      const mapped = OAUTH_SCOPE_TO_API_SCOPE[s]
      return mapped ? [mapped] : []
    })
}
