import { CardProps } from 'app/types'

async function upsertMissingTopicInDatabase(database: any, topic: string) {
  try {
    const { data, error } = await database.rpc('add_topics_or_increment_priority', {
      topic_names: [topic],
    })
    if (error) {
      console.error('Error incrementing generation priority:', error)
    }
  } catch (error) {
    console.error('Error calling RPC:', error)
  }
}

function MissingTopicCard(topic: string) {
  return {
    title: `No Cards Yet`,
    edited_contents: [
      'Message from Junwon',
      'You have reached a topic for which I have not yet had a chance to prepare great info cards. (Congratulations for reaching this far!)',
      `At your touch, \"${topic}\" was bumped up in priority. Junwon AI will work on gathering information and making cards for this topic before working on other topics.`,
      'Please grant me one more chance to try to satisfy you by checking again tomorrow. If you have any other asks, I am in the chatroom which you can reach by tapping on the logo icon at the top of this page!',
    ],
    topic: topic,
    id: '-1',
    topic_id: '-1',
    showElaborateOption: false,
  }
}

export async function getCardsOnTopic(database: any, topic: string) {
  const { data, error } = await database
    .from('cards')
    .select('*')
    .eq('topic', topic)
    .eq('is_presentable', true)
    .eq('is_discovery_card', false)
  if (error) {
    console.error('Error getting cards:', error)
    return []
  }
  if (data.length === 0) {
    await upsertMissingTopicInDatabase(database, topic)
    return [MissingTopicCard(topic)]
  } else {
    const { data: topic_record, error } = await database
      .from('topics')
      .select('*')
      .eq('topic', topic)
      .single()

    const introductionCard: CardProps = {
      id: `${topic}-introduction`,
      title: 'Introduction',
      edited_contents: [topic_record.intro],
      topic: topic,
      topic_id: topic_record.id,
      showElaborateOption: false,
    }
    data.unshift(introductionCard)

    return data
  }
}
