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

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

export const GetCardFileUploadUrlOutput = z.object({
  uploadUrl: z.string(),
  fileKey: z.string(),
  expiresAt: z.string(),
  uploadMethod: z.enum(['PUT', 'POST']).optional(),
  uploadHeaders: z.record(z.string(), z.string()).optional(),
})

export const getCardFileUploadUrl = pikkuSessionlessFunc({
  expose: true,
  description: 'Return a presigned upload URL for attaching a file to a card.',
  input: GetCardFileUploadUrlInput,
  output: GetCardFileUploadUrlOutput,
  func: async ({ content }, { cardId, fileName, contentType }) => {
    if (!content) {
      throw new Error('Content service not configured')
    }
    const fileKey = `${cardId}/${fileName}`
    const { uploadUrl, uploadMethod, uploadHeaders } = await content.getUploadURL({
      bucket: 'cards',
      fileKey,
      contentType,
    })
    return {
      uploadUrl,
      fileKey,
      expiresAt: new Date(Date.now() + 3_600_000).toISOString(),
      uploadMethod,
      uploadHeaders,
    }
  },
})
