import {open} from '@op-engineering/op-sqlite'
import {drizzle} from 'drizzle-orm/op-sqlite'
import {count} from 'drizzle-orm'
import {labelsTable, tasksTable} from '@/db/schema'

const opSqliteDb = open({
  name: 'todo.sqlite',
})

export const db = drizzle(opSqliteDb)

export async function seed() {
  const [{count: nbTasks}] = await db.select({count: count()}).from(tasksTable)

  if (nbTasks === 0) {
    await db.insert(tasksTable).values([
      ...Array(50)
        .fill(0)
        .map((_, i) => ({name: `Task ${i + 1}`, completed: i % 2 === 0})),
    ])
  }

  const [{count: nbLabels}] = await db.select({count: count()}).from(labelsTable)

  if (nbLabels === 0) {
    await db.insert(labelsTable).values([
      {name: 'Work', color: '#625b71'},
      {name: 'School', color: '#9a82db'},
      {name: 'Urgent', color: '#e46962'},
    ])
  }
}
