/**
 * OAuth Domain - Zod Validation Schemas
 *
 * Validation schemas for OAuth flow endpoints.
 * Includes path params and query params for authorize/callback flows.
 *
 * Security:
 * - All schemas use .strict() to prevent mass assignment attacks
 * - Provider enum validation prevents invalid providers
 * - OAuth code and state length limits prevent DoS
 * - organizationId validation prevents injection
 * - CSRF protection via state parameter validation
 */

import { z } from 'zod'
import { OAuthProviderSchema, OAuthCodeSchema, OAuthStateParamSchema, CredentialNameSchema } from '../../platform/utils/validation'

// ============================================================================
// Path Parameters
// ============================================================================

/**
 * Validate OAuth provider in URL path
 * Used by: GET /oauth/authorize/:provider, GET /oauth/callback/:provider
 *
 * Security: Enum validation prevents bypass attacks with invalid providers
 */
export const OAuthProviderParamSchema = z
  .object({
    provider: OAuthProviderSchema
  })
  .strict()

// ============================================================================
// Query Parameters - Authorize Flow
// ============================================================================

/**
 * OAuth authorize endpoint query parameters
 * GET /oauth/authorize/:provider?credentialName=...&organizationId=...
 *
 * Security:
 * - credentialName validated (alphanumeric + hyphens/underscores)
 * - organizationId required (public endpoint, can't use JWT)
 * - organizationId validated (string format for WorkOS/UUID)
 */
export const AuthorizeQuerySchema = z
  .object({
    credentialName: CredentialNameSchema,
    organizationId: z.string().min(1) // WorkOS org IDs or UUIDs
  })
  .strict()

// ============================================================================
// Query Parameters - Callback Flow
// ============================================================================

/**
 * OAuth callback endpoint query parameters
 * GET /oauth/callback/:provider?code=...&state=...&error=...
 *
 * Security:
 * - code length limited (10-1000 chars)
 * - state parameter validated (Base64-encoded JSON, max 2KB)
 * - error optional (provider-specific error codes)
 *
 * CSRF Protection:
 * - State parameter contains organizationId and credentialName
 * - State validated to ensure request originated from our authorize endpoint
 */
export const CallbackQuerySchema = z
  .object({
    code: OAuthCodeSchema.optional(),
    state: OAuthStateParamSchema.optional(),
    error: z.string().max(100).optional() // OAuth error codes (access_denied, etc.)
  })
  .passthrough() // OAuth2 spec: "client MUST ignore unrecognized response parameters"
  .refine(
    (data) => data.code || data.error,
    {
      message: 'Either code or error parameter must be provided'
    }
  )

// ============================================================================
// TypeScript Type Exports
// ============================================================================

// Export inferred types for use in route handlers
export type OAuthProviderParam = z.infer<typeof OAuthProviderParamSchema>
export type AuthorizeQuery = z.infer<typeof AuthorizeQuerySchema>
export type CallbackQuery = z.infer<typeof CallbackQuerySchema>
