import {z} from 'zod'

import {CrumbSchema} from './crumbs'
import {TrailPostAuthorSchema, TrailSchema} from './trails'

export type FeedItemType = 'crumb' | 'trail'

// one activity feed item: a crumb saved or a trail created. the id is
// prefixed with the type so mixed items stay unique in one list — the one
// definition both the api and clients derive item ids from
export const feedItemId = (
  type: FeedItemType,
  entityId: string,
): string => `${type}:${entityId}`

const FeedCrumbItemSchema = z.object({
  id: z.string(),
  type: z.literal('crumb'),
  author: TrailPostAuthorSchema,
  crumb: CrumbSchema,
  createdAt: z.iso.datetime(),
})

const FeedTrailItemSchema = z.object({
  id: z.string(),
  type: z.literal('trail'),
  author: TrailPostAuthorSchema,
  trail: TrailSchema,
  createdAt: z.iso.datetime(),
})

export const FeedItemSchema = z.discriminatedUnion('type', [
  FeedCrumbItemSchema,
  FeedTrailItemSchema,
])

export const FeedResponseSchema = z.object({
  items: z.array(FeedItemSchema),
  nextCursor: z.string().nullable(),
})

export type FeedItem = z.infer<typeof FeedItemSchema>
