import { z } from 'zod'
import { pikkuSessionlessFunc } from '#pikku'
import { randomUUID } from 'node:crypto'

export const OnCardEventTriggerInput = z.object({
  title: z.string(),
  status: z.enum(['todo', 'doing', 'done']).default('todo'),
  source: z.string().optional(),
})

export const OnCardEventTriggerOutput = z.object({
  cardId: z.string(),
  title: z.string(),
  status: z.string(),
})

export const onCardEventTrigger = pikkuSessionlessFunc({
  input: OnCardEventTriggerInput,
  output: OnCardEventTriggerOutput,
  remote: true,
  func: async ({ kysely, logger }, { title, status, source }) => {
    const cardId = randomUUID()
    const createdAt = new Date().toISOString()
    const max = await kysely
      .selectFrom('kanbanCard')
      .select(({ fn }) => fn.max<number>('position').as('max'))
      .where('status', '=', status)
      .executeTakeFirst()
    const position = (max?.max ?? 0) + 1
    await kysely
      .insertInto('kanbanCard')
      .values({ cardId, title, status, position, createdAt })
      .execute()
    logger.info(`onCardEventTrigger: created card ${cardId} from source=${source ?? 'unknown'}`)
    return { cardId, title, status }
  },
})
