import { z } from 'zod'
import { pikkuFunc } from '#pikku/pikku-types.gen.js'
import { isCompanyMember } from '../../lib/auth-helpers.js'
import { getTemplate } from '../../templates/index.js'

export const CreateResolutionInput = z.object({
  companyId: z.string(),
  templateKey: z.string(),
  title: z.string().min(2),
  fieldValues: z.record(z.string(), z.unknown()).default({}),
})

export const CreateResolutionOutput = z.object({ resolutionId: z.string() })

export const createResolution = pikkuFunc({
  expose: true,
  description: 'Create a draft resolution. Caller must be a company member.',
  input: CreateResolutionInput,
  output: CreateResolutionOutput,
  permissions: { member: [isCompanyMember] },
  func: async ({ kysely, audit }, data, { session }) => {
    const template = getTemplate(data.templateKey)
    if (!template) throw new Error(`Unknown template: ${data.templateKey}`)

    const row = await kysely
      .insertInto('resolution')
      .values({
        companyId: data.companyId,
        templateKey: data.templateKey,
        title: data.title,
        status: 'draft',
        fieldValues: JSON.stringify(data.fieldValues) as any,
        createdBy: session!.userId,
      })
      .returning(['resolutionId'])
      .executeTakeFirstOrThrow()

    await audit.onInsert('resolution', row.resolutionId, {
      companyId: data.companyId,
      templateKey: data.templateKey,
      title: data.title,
      status: 'draft',
      fieldValues: data.fieldValues,
    })
    return { resolutionId: row.resolutionId }
  },
})
