import type { Endpoint } from 'payload'
import { Storage } from '@google-cloud/storage'
import path from 'path'
import { fileURLToPath } from 'url'
import { gcsConfig } from '@/utilities/gcsConfig'

const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)

export const testUploadEndpoint: Endpoint = {
  path: '/test-upload-gcs',
  method: 'post',
  handler: async (req) => {
    // Auth check removed for troubleshooting

    const keyFilename = path.resolve(dirname, '../../gcs-credentials.json')

    try {
      const formData = await req.formData()
      const fileData = formData.get('file') as File
      
      if (!fileData) {
        return Response.json({ error: 'No file provided in field "file"' }, { status: 400 })
      }

      const storage = new Storage({
        projectId: process.env.GCS_PROJECT_ID || '',
        keyFilename,
      })

      const bucket = storage.bucket(gcsConfig.bucket)
      const destination = `${gcsConfig.prefix}/direct-test-${Date.now()}-${fileData.name}`
      const gcsFile = bucket.file(destination)
      
      const buffer = Buffer.from(await fileData.arrayBuffer())
      
      await gcsFile.save(buffer, {
        contentType: fileData.type,
        metadata: { cacheControl: 'no-cache' },
      })

      return Response.json({
        success: true,
        message: 'Direct API upload success',
        destination,
        url: `${gcsConfig.bucketBaseURL}/${destination}`,
      })
    } catch (uploadErr: any) {
      return Response.json({
        success: false,
        error: uploadErr.message,
        stack: uploadErr.stack,
      }, { status: 500 })
    }
  },
}
