import type { AdminStorageProvider, AdminStorageUploadInput } from '@admin/actions/storage/types' import { getClient } from '@admin/actions/railway-bucket/get-client' import { getConfig } from '@admin/actions/railway-bucket/get-config' import { stableReadUrl } from '@admin/actions/railway-bucket/stable-read-url' import { buildStorageObjectKey } from '@admin/actions/storage/object-key' import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' export const railwayBucketStorageProvider = { id: 'railway-bucket', isConfigured() { const config = getConfig() return Boolean( config.endpoint && config.accessKeyId && config.secretAccessKey && config.bucketName && config.region && config.urlStyle ) }, async saveFile(input: AdminStorageUploadInput) { const config = getConfig() if (!this.isConfigured()) { throw new Error('Railway Bucket is not fully configured.') } const key = buildStorageObjectKey(input.filename, input.prefix) await getClient().send( new PutObjectCommand({ Bucket: config.bucketName, Key: key, Body: input.buffer, ContentType: input.contentType, ContentLength: input.contentLength }) ) return { key, url: stableReadUrl(key) } }, async createReadUrl(key: string) { const config = getConfig() if (!this.isConfigured()) { throw new Error('Railway Bucket is not fully configured.') } return getSignedUrl( getClient(), new GetObjectCommand({ Bucket: config.bucketName, Key: key }), { expiresIn: 300 } ) } } satisfies AdminStorageProvider & { createReadUrl(key: string): Promise }