import type { OAuthProviderConfig } from './types'

/**
 * OAuth Provider Registry
 *
 * Add new integration = add config object here (no new code needed)
 *
 * Standard token exchange methods:
 * - basic-auth: client_id:client_secret in Authorization header
 * - form-encoded: credentials in URL-encoded body (Google)
 * - json-body: credentials in JSON body (most providers)
 *
 * Custom overrides for edge cases:
 * - customAuthFlow: Override authorization URL building
 * - customTokenExchange: Override token exchange logic
 */
export const OAUTH_PROVIDERS: Record<string, OAuthProviderConfig> = {
  'google-sheets': {
    id: 'google-sheets',
    name: 'Google Sheets',
    authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
    tokenUrl: 'https://oauth2.googleapis.com/token',
    authParams: {
      access_type: 'offline', // Required for refresh token
      prompt: 'consent' // Force consent to get refresh token on reconnect
    },
    tokenExchange: 'form-encoded',
    scopes: ['https://www.googleapis.com/auth/spreadsheets']
  },

  'google-calendar': {
    id: 'google-calendar',
    name: 'Google Calendar',
    authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
    tokenUrl: 'https://oauth2.googleapis.com/token',
    authParams: {
      access_type: 'offline', // Required for refresh token
      prompt: 'consent' // Force consent to get refresh token on reconnect
    },
    tokenExchange: 'form-encoded',
    scopes: ['https://www.googleapis.com/auth/calendar.readonly']
  },

  dropbox: {
    id: 'dropbox',
    name: 'Dropbox',
    authUrl: 'https://www.dropbox.com/oauth2/authorize',
    tokenUrl: 'https://api.dropboxapi.com/oauth2/token',
    authParams: {
      token_access_type: 'offline' // Required for refresh token
    },
    tokenExchange: 'form-encoded',
    scopes: ['files.content.write', 'files.content.read', 'files.metadata.write']
  }
}

/**
 * Get provider config by ID
 * @throws Error if provider not found
 */
export function getProviderConfig(providerId: string): OAuthProviderConfig {
  const config = OAUTH_PROVIDERS[providerId]
  if (!config) {
    throw new Error(`Unknown OAuth provider: ${providerId}`)
  }
  return config
}

/**
 * List all available providers (for frontend)
 */
export function listProviders(): OAuthProviderConfig[] {
  return Object.values(OAUTH_PROVIDERS)
}
