import { z } from 'zod'

/**
 * Credential field definition
 */
export interface CredentialField {
  key: string
  label: string
  type: 'password' | 'text'
  required: boolean
  placeholder?: string
  description?: string
}

/**
 * Credential schema definition
 */
export interface CredentialSchema {
  type: string
  label: string
  description: string
  fields?: CredentialField[]
  docsUrl?: string
  nameSuggestions: string[]
  oauthProvider?: string // For OAuth types
}

/**
 * Zod schemas for runtime validation
 */
const CredentialFieldSchema = z.object({
  key: z.string(),
  label: z.string(),
  type: z.enum(['password', 'text']),
  required: z.boolean(),
  placeholder: z.string().optional(),
  description: z.string().optional()
})

const CredentialSchemaZod = z.object({
  type: z.string(),
  label: z.string(),
  description: z.string(),
  fields: z.array(CredentialFieldSchema).optional(),
  docsUrl: z.string().url().optional(),
  nameSuggestions: z.array(z.string()),
  oauthProvider: z.string().optional()
})

/**
 * Credential Schema Registry
 *
 * Add new integration = add schema object here (no modal changes needed)
 *
 * Schema types:
 * - oauth: OAuth-based authentication (handled via OAuth flow)
 * - single_field: Single API key field (generic)
 */
export const CREDENTIAL_SCHEMAS: Record<string, CredentialSchema> = {
  'google-sheets': {
    type: 'oauth',
    label: 'Google Sheets',
    description: 'Google Sheets OAuth integration',
    oauthProvider: 'google-sheets',
    nameSuggestions: ['google-sheets-prod', 'google-sheets-dev', 'sheets-workspace']
  },

  dropbox: {
    type: 'oauth',
    label: 'Dropbox',
    description: 'Dropbox OAuth integration',
    oauthProvider: 'dropbox',
    nameSuggestions: ['dropbox-prod', 'dropbox-dev', 'elevasis-dropbox']
  },

  oauth: {
    type: 'oauth',
    label: 'OAuth',
    description: 'Generic OAuth credential',
    nameSuggestions: []
  },

  'api-key': {
    type: 'single_field',
    label: 'API Key',
    description: 'Single-field API key credential',
    fields: [
      {
        key: 'apiKey',
        label: 'API Key',
        type: 'password',
        required: true,
        placeholder: 'Enter your API key',
        description: 'API key for the service'
      }
    ],
    nameSuggestions: ['service-prod', 'service-dev', 'api-key']
  },

  'webhook-secret': {
    type: 'single_field',
    label: 'Webhook Secret',
    description: 'Webhook signing secret for signature validation',
    fields: [
      {
        key: 'signingSecret',
        label: 'Signing Secret',
        type: 'password',
        required: true,
        placeholder: 'whsec_...',
        description: 'Webhook signing secret from provider dashboard'
      }
    ],
    nameSuggestions: ['my-org-cal-com-webhook', 'my-org-stripe-webhook', 'my-org-signature-api-webhook']
  },

  'api-key-secret': {
    type: 'api-key-secret',
    label: 'API Key + Secret',
    description: 'API key and secret pair authentication',
    fields: [
      {
        key: 'apiKey',
        label: 'API Key',
        type: 'password',
        required: true
      },
      {
        key: 'apiSecret',
        label: 'API Secret',
        type: 'password',
        required: true
      }
    ],
    nameSuggestions: []
  },

  apify: {
    type: 'single_field',
    label: 'Apify',
    description: 'Apify API token for running web-scraping actors (e.g. website crawl, Google Places scrape).',
    fields: [
      {
        key: 'apiKey',
        label: 'API Token',
        type: 'password',
        required: true,
        placeholder: 'apify_api_...',
        description: 'Personal API token from https://console.apify.com/account/integrations'
      }
    ],
    docsUrl: 'https://docs.apify.com/platform/integrations/api',
    nameSuggestions: ['elevasis-apify', 'apify-prod', 'apify-dev']
  },

  clickup: {
    type: 'single_field',
    label: 'ClickUp',
    description: 'ClickUp personal API token for creating tasks in tenant-managed ClickUp workspaces.',
    fields: [
      {
        key: 'apiToken',
        label: 'API Token',
        type: 'password',
        required: true,
        placeholder: 'pk_...',
        description: 'Personal API token from ClickUp settings. Personal tokens start with pk_.'
      }
    ],
    docsUrl: 'https://developer.clickup.com/docs/authentication',
    nameSuggestions: ['clickup-demo', 'clickup-prod', 'clickup-dev']
  }
}

/**
 * Get credential schema by type
 * @param type - Credential type identifier
 * @returns Validated credential schema
 * @throws ZodError if schema is malformed
 */
export function getCredentialSchema(type: string): CredentialSchema {
  const schema = CREDENTIAL_SCHEMAS[type] || CREDENTIAL_SCHEMAS['api-key']
  return CredentialSchemaZod.parse(schema)
}

/**
 * List all available credential types (for frontend dropdown)
 * @returns Array of credential schemas
 */
export function listCredentialSchemas(): CredentialSchema[] {
  return Object.values(CREDENTIAL_SCHEMAS)
}

/**
 * Get all credential type identifiers
 * @returns Array of type strings
 */
export function getCredentialTypes(): string[] {
  return Object.keys(CREDENTIAL_SCHEMAS)
}
