import type {
  PublicUser,
  Trail,
  TrailDetail,
  TrailPost,
} from '@crumbs/core/schemas'

// best-effort local renders of trails and posts created offline: enough shape
// to show in lists and open in detail the instant they're saved, and schema-
// valid so they survive a snapshot round-trip across a cold start. server-
// derived fields fill in when the queued create replays and the server copy
// replaces them by id — mirrors optimistic-crumb for the crumbs flagship

export type Author = Pick<PublicUser, 'id' | 'handle' | 'avatarUrl'>

export const optimisticTrail = (
  name: string,
  {id, author, now}: {id: string; author: Author; now: string},
): Trail => ({
  id,
  authorId: author.id,
  authorHandle: author.handle,
  authorAvatarUrl: author.avatarUrl,
  name,
  description: null,
  coverImageUrl: null,
  crumbCount: 0,
  pinned: false,
  unseenCount: 0,
  members: [],
  createdAt: now,
  updatedAt: now,
})

// the detail seeded on create so opening the just-made trail renders at once
// offline — the creator is its owner, everything else empty until the crumbs,
// posts and collaborators it later gains sync
export const optimisticTrailDetail = (
  name: string,
  meta: {id: string; author: Author; now: string},
): TrailDetail => ({
  ...optimisticTrail(name, meta),
  crumbs: [],
  collaborators: [],
  viewerRole: 'owner',
  posts: [],
})

// mentions are resolved server-side, so facets stay empty (unhighlighted)
// until the queued create replays and the server copy fills them in
export const optimisticTrailPost = (
  text: string,
  {id, author, now}: {id: string; author: Author; now: string},
): TrailPost => ({
  id,
  text,
  facets: [],
  author: {
    id: author.id,
    handle: author.handle,
    avatarUrl: author.avatarUrl,
  },
  createdAt: now,
})
