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

export const GetResolutionPdfUrlInput = z.object({ resolutionId: z.string() })
export const GetResolutionPdfUrlOutput = z.object({ url: z.string() })

export const getResolutionPdfUrl = pikkuFunc({
  expose: true,
  description: 'Return a signed URL for the resolution PDF. Caller must be a member.',
  input: GetResolutionPdfUrlInput,
  output: GetResolutionPdfUrlOutput,
  permissions: { member: [isCompanyMember] },
  func: async ({ kysely, content }, { resolutionId }) => {
    const r = await kysely
      .selectFrom('resolution')
      .select(['pdfKey'])
      .where('resolutionId', '=', resolutionId)
      .executeTakeFirstOrThrow()
    if (!r.pdfKey) throw new Error('Resolution has no PDF yet')
    const url = await content.signContentKey({
      bucket: 'resolutions',
      contentKey: r.pdfKey,
      dateLessThan: new Date(Date.now() + 3600 * 1000),
    })
    return { url }
  },
})
