<template>
  <router-view
    v-if="timeslot && note"
    :show="show"
    :timeslot="timeslot"
    :note="note"
    :playlist="playlist"
  />
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { useObjectFromStore } from '@rokoli/bnb/drf'
import { Show } from '@/types'
import { useNoteStore, usePlaylistStore, useTimeSlotStore } from '@/stores'
import { watchEffect } from 'vue'
import { defineNavigationContext } from '@/stores/nav'
import { newNote } from '@/stores/notes'

const props = defineProps<{
  show: Show
}>()

const router = useRouter()
const route = useRoute()
const timeslotStore = useTimeSlotStore()
const noteStore = useNoteStore()
const playlistStore = usePlaylistStore()
const { obj: timeslot } = useObjectFromStore(
  () => parseInt(route.params.episodeId as string),
  timeslotStore,
)
const { obj: note } = useObjectFromStore(() => timeslot.value?.noteId ?? null, noteStore)
const { obj: playlist } = useObjectFromStore(
  () => timeslot.value?.playlistId ?? null,
  playlistStore,
)

defineNavigationContext(() => ({ episode: timeslot }))

// TODO: remove once steering auto-creates notes for timeslots
watchEffect(async () => {
  const ts = timeslot.value
  if (ts && ts.noteId === null) {
    const note = newNote(ts.id, props.show)
    note.title = 'A title...'
    note.content = 'Some content...'
    const savedNote = await noteStore.create(note)
    await timeslotStore.partialUpdate(ts.id, { noteId: savedNote.id })
  }
})

watchEffect(() => {
  const showId = timeslot.value?.showId
  // if timeslot.showId doesn’t match the provided show.id,
  // the user might have switched shows with the show selector.
  if (showId && showId !== props.show.id) {
    void router.push({ name: 'show', params: { showId: props.show.id.toString() } })
  }
})
</script>