import { z } from 'zod';
import {
  BaseEcosystemEventSchema,
  TimelineItemSchema,
  TimelineVisibilitySchema,
} from '@bytelyst/events';

export const TimelineItemDocSchema = z.object({
  id: z.string().min(1),
  productId: z.string().min(1),
  userId: z.string().min(1).nullable().optional(),
  orgId: z.string().min(1).nullable().optional(),
  eventId: z.string().min(1),
  eventName: z.string().min(1),
  artifactId: z.string().min(1).nullable().optional(),
  correlationId: z.string().min(1).nullable().optional(),
  actorType: z.enum(['user', 'agent', 'system', 'device']),
  visibility: TimelineVisibilitySchema,
  occurredAt: z.string().datetime(),
  item: TimelineItemSchema,
  createdAt: z.string().datetime(),
  updatedAt: z.string().datetime(),
});

export type TimelineItemDoc = z.infer<typeof TimelineItemDocSchema> & {
  _ts?: number;
  _etag?: string;
};

export const IngestTimelineEventsSchema = z.object({
  userId: z.string().min(1).nullable().optional(),
  visibility: TimelineVisibilitySchema.optional(),
  events: z.array(BaseEcosystemEventSchema).min(1),
});

export type IngestTimelineEventsInput = z.infer<typeof IngestTimelineEventsSchema>;

export const ListTimelineQuerySchema = z.object({
  userId: z.string().min(1).optional(),
  correlationId: z.string().min(1).optional(),
  artifactId: z.string().min(1).optional(),
  eventName: z.string().min(1).optional(),
  limit: z.coerce.number().int().min(1).max(100).default(50),
});

export type ListTimelineQuery = z.infer<typeof ListTimelineQuerySchema>;
