import { z } from 'zod'

// ---------------------------------------------------------------------------
// Platform event member schemas (9 members — closed union, stays in @repo/core)
//
// Domain-specific events (reply_received, booking_nudge_sent, etc.) live in
// @repo/elevasis-operations as CrmDomainActivityEventSchema.
// See Open Decision #5 in crm-action-system.mdx for rationale.
// ---------------------------------------------------------------------------

const StageChangeEventSchema = z.object({
  type: z.literal('stage_change'),
  timestamp: z.string().datetime(),
  stageBefore: z.string(),
  stageAfter: z.string(),
  reason: z.string().optional()
})

const StateChangeEventSchema = z.object({
  type: z.literal('state_change'),
  timestamp: z.string().datetime(),
  stateBefore: z.string().nullable(),
  stateAfter: z.string().nullable(),
  reason: z.string().optional()
})

const ActionTakenEventSchema = z.object({
  type: z.literal('action_taken'),
  timestamp: z.string().datetime(),
  actionKey: z.string(),
  payload: z.record(z.string(), z.unknown()).optional()
})

const ApprovalCreatedEventSchema = z.object({
  type: z.literal('approval_created'),
  timestamp: z.string().datetime(),
  commandId: z.string(),
  dealStageBefore: z.string().optional(),
  dealStageAfter: z.string().optional()
})

const ApprovalResolvedEventSchema = z.object({
  type: z.literal('approval_resolved'),
  timestamp: z.string().datetime(),
  commandId: z.string(),
  resolution: z.enum(['superseded']),
  originResourceType: z.string().optional()
})

const ApprovalStaleEventSchema = z.object({
  type: z.literal('approval_stale'),
  timestamp: z.string().datetime(),
  commandId: z.string(),
  dealStageBefore: z.string().optional(),
  dealStageAfter: z.string().optional()
})

const TaskCreatedEventSchema = z.object({
  type: z.literal('task_created'),
  timestamp: z.string().datetime(),
  taskId: z.string()
})

const DealCreatedEventSchema = z.object({
  type: z.literal('deal_created'),
  timestamp: z.string().datetime()
})

const ActionFailedEventSchema = z.object({
  type: z.literal('action_failed'),
  timestamp: z.string().datetime(),
  actionKey: z.string(),
  errorMessage: z.string(),
  payload: z.record(z.string(), z.unknown()).optional()
})

// ---------------------------------------------------------------------------
// Union — closed 9-member platform union
// ---------------------------------------------------------------------------

export const ActivityEventSchema = z.discriminatedUnion('type', [
  StageChangeEventSchema,
  StateChangeEventSchema,
  ActionTakenEventSchema,
  ApprovalCreatedEventSchema,
  ApprovalResolvedEventSchema,
  ApprovalStaleEventSchema,
  TaskCreatedEventSchema,
  DealCreatedEventSchema,
  ActionFailedEventSchema
])

export type ActivityEvent = z.infer<typeof ActivityEventSchema>
