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

export const CreateCardInput = z.object({
  title: z.string().min(1),
  status: z.enum(['todo', 'doing', 'done']).default('todo'),
  priority: z.enum(['low', 'medium', 'high']).default('medium').optional(),
})

export const CreateCardOutput = z.object({
  cardId: z.string(),
  title: z.string(),
  status: z.string(),
  position: z.number(),
  createdAt: z.string(),
})

export const createCard = pikkuSessionlessFunc({
  inline: false,
  expose: true,
  description: 'Create a kanban card.',
  input: CreateCardInput,
  output: CreateCardOutput,
  func: async ({ kysely, logger, queueService }, { title, status }) => {
    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()

    await queueService.add('process-card-event', { cardId, action: 'created', status, createdAt })

    logger.info(`createCard ${cardId} (${status})`)
    return { cardId, title, status, position, createdAt }
  },
})
