/**
 * Zod validation schemas for execution and workflow domain API endpoints
 * @module execution/api-schemas
 *
 * These schemas provide runtime validation for the most critical API endpoints:
 * - External API /execute (public-facing, API key auth)
 * - Execution Engine /execute (internal, JWT auth)
 * - Command Queue (human-in-the-loop approvals)
 * - Sessions (conversational agents)
 *
 * Security Features:
 * - UUID validation prevents injection attacks
 * - Payload size limits prevent DoS attacks
 * - Strict mode blocks field injection (e.g., organizationId)
 * - Enum validation ensures type safety at runtime
 */

import { z } from 'zod'
import {
  UuidSchema,
  NonEmptyStringSchema,
  ResourceTypeSchema,
  OriginResourceTypeSchema,
  createPayloadSizeValidator
} from '../../platform/utils/validation'

// Payload size constraint (500KB limit for execution payloads)
const PayloadSchema = createPayloadSizeValidator(500_000) // Required by default
const OptionalPayloadSchema = createPayloadSizeValidator(500_000, { optional: true })

// ============================================================================
// EXECUTION TARGET SCHEMAS
// ============================================================================

/**
 * Execution target validation
 * Used by: Task Scheduler, Command Queue, Direct Execution
 *
 * Security:
 * - resourceId validated as non-empty string (allows workflow/agent names)
 * - resourceType enum validated at runtime
 * - payload size limited to 500KB (prevents DoS)
 */
export const ExecutionTargetSchema = z
  .object({
    resourceType: ResourceTypeSchema,
    resourceId: NonEmptyStringSchema.max(255),
    payload: OptionalPayloadSchema
  })
  .strict()

/**
 * Origin tracking validation
 * Required for audit trails and execution lineage
 *
 * Security:
 * - originExecutionId validated as UUID
 * - originResourceType enum validated
 * - originResourceId length limited
 */
export const OriginTrackingSchema = z
  .object({
    originExecutionId: UuidSchema,
    originResourceType: OriginResourceTypeSchema,
    originResourceId: NonEmptyStringSchema.max(100)
  })
  .strict()

// ============================================================================
// EXTERNAL API SCHEMAS (CRITICAL - PUBLIC FACING)
// ============================================================================

/**
 * External API /execute endpoint validation
 * CRITICAL: This is a public-facing endpoint using API key auth
 *
 * Only production workflows can be executed via external API (in production env).
 * Production status check happens at service layer after resource lookup.
 *
 * Security Features:
 * - resourceId validated as non-empty string (kebab-case resource names)
 * - 500KB payload limit prevents memory exhaustion
 * - Strict mode blocks organizationId injection
 *
 * @example
 * ```typescript
 * // Valid request
 * {
 *   resourceId: "lead-qualification-agent",
 *   input: { message: "Hello" }
 * }
 *
 * // Invalid - will be rejected
 * {
 *   resourceId: "", // Empty string not allowed
 *   input: "x".repeat(600_000) // Exceeds 500KB
 * }
 * ```
 */
export const ExternalExecuteRequestSchema = z
  .object({
    resourceId: NonEmptyStringSchema.max(100),
    input: OptionalPayloadSchema
  })
  .strict()

/**
 * External API /execute response schema
 * Validates success/error response structure
 */
export const ExternalExecuteResponseSchema = z.union([
  z.object({
    executionId: UuidSchema,
    success: z.literal(true),
    data: z.unknown()
  }),
  z.object({
    success: z.literal(false),
    error: z.string(),
    message: z.string()
  })
])

// ============================================================================
// AI ENGINE SCHEMAS (CRITICAL - INTERNAL EXECUTION)
// ============================================================================

/**
 * Execution Engine /execute endpoint validation
 * CRITICAL: Controls agent/workflow execution in authenticated context
 *
 * Security Features:
 * - resourceType enum validated at runtime (not just TypeScript)
 * - resourceId validated as non-empty string (kebab-case pattern)
 * - Optional input with size constraint (500KB)
 * - Strict mode prevents field injection
 *
 * @example
 * ```typescript
 * // Valid workflow execution
 * {
 *   resourceType: "workflow",
 *   resourceId: "linear-test-workflow",
 *   input: { data: "test" }
 * }
 *
 * // Valid agent execution (no input)
 * {
 *   resourceType: "agent",
 *   resourceId: "basic-agent"
 * }
 *
 * // Invalid - will be rejected
 * {
 *   resourceType: "malicious", // Invalid enum
 *   resourceId: "" // Empty string not allowed
 * }
 * ```
 */
export const ExecutionEngineExecuteRequestSchema = z
  .object({
    resourceType: ResourceTypeSchema,
    resourceId: NonEmptyStringSchema.max(100),
    input: OptionalPayloadSchema
  })
  .strict()

/**
 * Execution Engine /execute response schema
 * Validates success/error response structure with execution logs
 */
export const ExecutionEngineExecuteResponseSchema = z.union([
  z.object({
    success: z.literal(true),
    executionId: UuidSchema,
    logs: z.array(z.unknown()),
    data: z.unknown().nullable()
  }),
  z.object({
    success: z.literal(false),
    executionId: UuidSchema,
    logs: z.array(z.unknown()),
    error: z.object({
      message: z.string(),
      code: z.string(),
      details: z.string().optional(),
      suggestions: z.array(z.string()).optional()
    })
  })
])

// ============================================================================
// COMMAND QUEUE SCHEMAS (HUMAN-IN-THE-LOOP)
// ============================================================================

/**
 * Create command queue task (approval request)
 *
 * Security Features:
 * - All UUIDs validated
 * - Execution targets validated (nested validation)
 * - Payload sizes limited (both initial and targets)
 * - Description and notes length limited
 *
 * @example
 * ```typescript
 * {
 *   originExecutionId: "550e8400-e29b-41d4-a716-446655440000",
 *   originResourceType: "agent",
 *   originResourceId: "approval-agent",
 *   approveTarget: {
 *     resourceType: "workflow",
 *     resourceId: "550e8400-e29b-41d4-a716-446655440001",
 *     payload: { approved: true }
 *   },
 *   payloadInitial: { request: "approval needed" },
 *   description: "Approve workflow execution",
 *   priority: 5
 * }
 * ```
 */
export const CreateCommandQueueTaskSchema = z
  .object({
    // Origin tracking
    originExecutionId: UuidSchema,
    originResourceType: OriginResourceTypeSchema,
    originResourceId: NonEmptyStringSchema.max(100),

    // Approval targets
    approveTarget: ExecutionTargetSchema,
    rejectTarget: ExecutionTargetSchema.optional(),

    // Task metadata
    description: NonEmptyStringSchema.max(1000).optional(),
    priority: z.number().int().min(1).max(10).default(5),
    expiresAt: z.string().datetime().optional(),

    // Initial payload
    payloadInitial: PayloadSchema
  })
  .strict()

/**
 * Submit decision on command queue task
 *
 * Security Features:
 * - Decision enum validated (only 'approve' | 'reject')
 * - Notes length limited to 5000 characters
 * - Payload override size limited to 500KB
 *
 * @example
 * ```typescript
 * // Approval with notes
 * {
 *   decision: "approve",
 *   notes: "Looks good to proceed"
 * }
 *
 * // Rejection with payload override
 * {
 *   decision: "reject",
 *   notes: "Missing required data",
 *   payloadOverride: { reason: "incomplete" }
 * }
 * ```
 */
export const SubmitDecisionSchema = z
  .object({
    decision: z.enum(['approve', 'reject']),
    notes: NonEmptyStringSchema.max(5000).optional(),
    payloadOverride: OptionalPayloadSchema
  })
  .strict()

/**
 * List command queue tasks
 * Query parameters for filtering tasks by status
 */
export const ListCommandQueueTasksSchema = z
  .object({
    status: z.enum(['pending', 'approved', 'rejected', 'expired']).optional(),
    limit: z.coerce.number().int().min(1).max(100).default(20)
  })
  .strict()

// ============================================================================
// SESSION SCHEMAS (CONVERSATIONAL AGENTS)
// ============================================================================

// ============================================================================
// EXECUTION MANAGEMENT SCHEMAS
// ============================================================================

/**
 * List executions query parameters
 * Filter executions by resource status (dev/prod/all)
 */
export const ListExecutionsSchema = z
  .object({
    resourceStatus: z.enum(['dev', 'prod', 'all']).default('all')
  })
  .strict()

/**
 * Delete execution(s) query parameters
 * Optional filter by resource status when bulk deleting
 */
export const DeleteExecutionsSchema = z
  .object({
    resourceStatus: z.enum(['dev', 'prod']).optional()
  })
  .strict()
