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

export const GetResolutionInput = z.object({ resolutionId: z.string() })
export const GetResolutionOutput = z.object({
  resolutionId: z.string(),
  companyId: z.string(),
  templateKey: z.string(),
  title: z.string(),
  status: z.enum(['draft', 'published', 'archived']),
  fieldValues: z.record(z.string(), z.unknown()),
  pdfKey: z.string().nullable(),
  createdAt: z.string(),
  publishedAt: z.string().nullable(),
})

export const getResolution = pikkuFunc({
  expose: true,
  description: 'Fetch a resolution by id.',
  input: GetResolutionInput,
  output: GetResolutionOutput,
  permissions: { member: [isCompanyMember] },
  func: async ({ kysely }, { resolutionId }) => {
    const r = await kysely
      .selectFrom('resolution')
      .selectAll()
      .where('resolutionId', '=', resolutionId)
      .executeTakeFirstOrThrow()
    return {
      resolutionId: r.resolutionId,
      companyId: r.companyId,
      templateKey: r.templateKey,
      title: r.title,
      status: r.status,
      fieldValues: (r.fieldValues as any) ?? {},
      pdfKey: r.pdfKey,
      createdAt: r.createdAt,
      publishedAt: r.publishedAt,
    } as any
  },
})
