import { create } from 'zustand'
import type { ErrorLogEntry } from '@shared/ipc'
import { isPreview as PREVIEW } from '../isPreview'
import { logError } from '../reportError'

// Sample entries so the Diagnostics card has content during UI design.
const seed: ErrorLogEntry[] = PREVIEW
  ? [
      {
        id: 'e1',
        title: 'Private video',
        url: 'https://youtube.com/watch?v=err0r',
        kind: 'video',
        error: '[youtube] err0r: Private video. Sign in if you have access.',
        occurredAt: Date.now() - 1000 * 60 * 12
      },
      {
        id: 'e2',
        title: 'you’re about to get hacked!! (7 reasons why)',
        url: 'https://youtube.com/watch?v=q2err0r',
        kind: 'video',
        error:
          'Postprocessing: Conversion failed! — [ModifyChapters] Re-encoding "video.mp4" with appropriate keyframes',
        detail: [
          '[info] q2err0r: Downloading 1 format(s): 137+251',
          '[SponsorBlock] Found 1 segments in the SponsorBlock database',
          '[Merger] Merging formats into "video.mp4"',
          '[ModifyChapters] Re-encoding "video.mp4" with appropriate keyframes',
          '[ModifyChapters] Removing chapters from video.mp4',
          'ERROR: Postprocessing: Conversion failed!'
        ].join('\n'),
        occurredAt: Date.now() - 1000 * 60 * 5
      }
    ]
  : []

interface ErrorLogState {
  entries: ErrorLogEntry[]
  clear: () => void
}

export const useErrorLog = create<ErrorLogState>((set) => ({
  entries: seed,

  clear: () => {
    set({ entries: [] })
    if (!PREVIEW) window.api.clearErrorLog().catch(logError('clearErrorLog'))
  }
}))

// Load the persisted error log on startup.
if (!PREVIEW) {
  window.api.listErrorLog().then((entries) => useErrorLog.setState({ entries }))
}
