import { z } from 'zod'
import { NonEmptyStringSchema } from '../../platform/utils/validation'

/**
 * Activity Log API Validation Schemas
 *
 * Zod schemas for Activity Log endpoints with security controls:
 * - Mass assignment prevention (.strict() mode)
 * - Size limits (title: 200 chars, description: 1000 chars)
 * - Enum validation (activityType, status)
 * - Metadata size limits (50KB)
 */

// Activity type enum
export const ActivityTypeSchema = z.enum([
  'workflow_execution',
  'agent_run',
  'hitl_action',
  'webhook_received',
  'webhook_executed',
  'webhook_failed',
  'credential_change',
  'credential_read',
  'api_key_change',
  'deployment_change',
  'membership_change'
])

// Activity status enum
export const ActivityStatusSchema = z.enum(['success', 'failure', 'pending', 'approved', 'rejected', 'completed'])

// Metadata schema with size limit (50KB)
const MetadataSchema = z
  .record(z.string(), z.unknown())
  .refine((val) => JSON.stringify(val).length <= 50_000, 'Metadata exceeds 50KB limit')
  .optional()

// POST /api/activities - Create activity
export const CreateActivitySchema = z
  .object({
    activityType: ActivityTypeSchema,
    status: ActivityStatusSchema,
    title: NonEmptyStringSchema.max(200),
    description: z.string().max(1000).optional(),
    entityType: NonEmptyStringSchema.max(100),
    entityId: NonEmptyStringSchema.max(255),
    entityName: z.string().max(255).optional(),
    metadata: MetadataSchema,
    occurredAt: z.string().datetime().optional(),
    actorId: z.string().uuid().optional(),
    actorType: z.enum(['user', 'system', 'api_key']).optional()
    // NO organizationId (always from JWT/API key context)
  })
  .strict()

// GET /api/activities/trend - Activity trend timestamps query params
export const ActivityTrendQuerySchema = z
  .object({
    activityType: ActivityTypeSchema.optional(),
    entityType: z.string().max(100).optional(),
    entityId: z.string().max(255).optional(),
    startDate: z.string().datetime().optional(),
    endDate: z.string().datetime().optional()
  })
  .strict()

// GET /api/activities - List activities query params
export const ListActivitiesQuerySchema = z
  .object({
    limit: z.coerce.number().int().min(1).max(100).default(50),
    offset: z.coerce.number().int().min(0).default(0),
    activityType: ActivityTypeSchema.optional(),
    entityType: z.string().max(100).optional(),
    entityId: z.string().max(255).optional(),
    startDate: z.string().datetime().optional(),
    endDate: z.string().datetime().optional(),
    status: ActivityStatusSchema.optional(),
    search: z.string().max(200).optional()
  })
  .strict()
