import { S3Client, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';
import { env } from './env';
import crypto from 'crypto';

// Initialize S3 client for Cloudflare R2
const r2Client = new S3Client({
    region: 'auto',
    endpoint: `https://${env.R2_ACCOUNT_ID || 'placeholder'}.r2.cloudflarestorage.com`,
    credentials: {
        accessKeyId: env.R2_ACCESS_KEY_ID || '',
        secretAccessKey: env.R2_SECRET_ACCESS_KEY || '',
    },
});

export async function uploadFileToR2(
    file: Buffer,
    filename: string,
    contentType: string = 'application/pdf'
): Promise<string> {
    // Generate a unique key for the file
    const ext = filename.split('.').pop() || 'pdf';
    const randomId = crypto.randomBytes(8).toString('hex');
    const timestamp = Date.now();
    const key = `uploads/${timestamp}_${randomId}.${ext}`;

    await r2Client.send(
        new PutObjectCommand({
            Bucket: env.R2_BUCKET_NAME,
            Key: key,
            Body: file,
            ContentType: contentType,
            ContentDisposition: `inline; filename="${filename}"`,
            // Cache for 1 year, as these are static files
            CacheControl: 'public, max-age=31536000',
        })
    );

    // Return the public URL
    // If R2_PUBLIC_URL is set, use it (custom domain or r2.dev subdomain)
    // Otherwise, construct a fallback (which might not work without public access enabled on bucket)
    const publicUrl = env.R2_PUBLIC_URL
        ? `${env.R2_PUBLIC_URL}/${key}`
        : `https://${env.R2_BUCKET_NAME}.r2.dev/${key}`;

    return publicUrl;
}

export async function deleteFileFromR2(fileUrl: string): Promise<void> {
    try {
        // Extract key from URL
        // URL format: https://domain.com/uploads/filename.pdf
        const url = new URL(fileUrl);
        const key = url.pathname.substring(1); // Remove leading slash

        await r2Client.send(
            new DeleteObjectCommand({
                Bucket: env.R2_BUCKET_NAME,
                Key: key,
            })
        );
    } catch (error) {
        console.error('Error deleting file from R2:', error);
        // Suppress error, as deletion failure shouldn't block main flow
    }
}
