import { z } from 'zod'
import { pikkuSessionlessFunc } from '#pikku'

export const SignCardFileInput = z.object({
  cardId: z.string().min(1),
  fileName: z.string().min(1),
})

export const SignCardFileOutput = z.object({
  signedUrl: z.string(),
  expiresAt: z.string(),
})

export const signCardFile = pikkuSessionlessFunc({
  expose: true,
  description: 'Return a time-limited signed download URL for a card attachment.',
  input: SignCardFileInput,
  output: SignCardFileOutput,
  func: async ({ content }, { cardId, fileName }) => {
    if (!content) {
      throw new Error('Content service not configured')
    }
    const fileKey = `${cardId}/${fileName}`
    const dateLessThan = new Date(Date.now() + 3_600_000)
    const signedUrl = await content.signContentKey({
      bucket: 'cards',
      contentKey: fileKey,
      dateLessThan,
    })
    return {
      signedUrl,
      expiresAt: dateLessThan.toISOString(),
    }
  },
})
