import {CrumbSchema} from '@crumbs/core/schemas'
import {describe, expect, test} from 'bun:test'

import {emptyDraft} from '@/lib/draft'
import {optimisticCrumb} from '@/lib/optimistic-crumb'

const meta = {
  id: '11111111-1111-4111-8111-111111111111',
  authorId: '22222222-2222-4222-8222-222222222222',
  now: '2026-07-03T00:00:00.000Z',
}

describe('optimisticCrumb', () => {
  test('is CrumbSchema-valid so it survives a snapshot round-trip', () => {
    const draft = {
      ...emptyDraft,
      name: 'Blue Bottle',
      tags: ['coffee'],
    }
    const crumb = optimisticCrumb(draft, draft.tags, meta)
    // the snapshot layer reads through fromSchema(CrumbSchema); an invalid
    // optimistic crumb would be silently dropped on the next cold start
    expect(CrumbSchema.safeParse(crumb).success).toBe(true)
  })

  test('renders tags with the shared server emoji map', () => {
    const draft = {
      ...emptyDraft,
      name: 'x',
      tags: ['coffee', 'zzznotarealtag'],
    }
    const crumb = optimisticCrumb(draft, draft.tags, meta)
    expect(crumb.tags).toEqual([
      {name: 'coffee', emoji: '☕'},
      // unknown tags fall back to the default pin, never crash
      {name: 'zzznotarealtag', emoji: '📍'},
    ])
  })

  test('carries an already-resolved place, else null until sync', () => {
    const place = {
      id: '33333333-3333-4333-8333-333333333333',
      name: 'Blue Bottle',
      latitude: 1,
      longitude: 2,
      address: null,
      category: 'coffee',
      status: 'canonical' as const,
    }
    expect(
      optimisticCrumb({...emptyDraft, place}, [], meta).place,
    ).toEqual(place)
    expect(optimisticCrumb(emptyDraft, [], meta).place).toBeNull()
  })
})
