import { requireAuth } from '~/server/utils/auth';
import { getPreviewUrl } from '~/server/utils/minio';
import mime from 'mime-types';

export default defineEventHandler(async (event) => {
  // Check authentication (x-tag header OR Keycloak session)
  await requireAuth(event);
  
  try {
    const query = getQuery(event);
    const fileName = query.fileName as string;
    
    if (!fileName) {
      throw createError({
        statusCode: 400,
        statusMessage: 'File name is required',
      });
    }
    
    // Get content type
    const contentType = mime.lookup(fileName) || 'application/octet-stream';
    
    // Check if file type supports preview
    const supportedPreviewTypes = [
      'image/jpeg',
      'image/jpg',
      'image/png',
      'image/gif',
      'image/svg+xml',
      'image/webp',
      'application/pdf',
    ];
    
    if (!supportedPreviewTypes.includes(contentType)) {
      throw createError({
        statusCode: 400,
        statusMessage: 'File type does not support preview',
      });
    }
    
    // Generate presigned URL for preview
    const url = await getPreviewUrl(fileName, contentType);
    
    console.log('Preview URL generated:', {
      fileName,
      contentType,
      url: url.substring(0, 100) + '...' // Log first 100 chars for security
    });
    
    return {
      success: true,
      url,
      fileName,
      contentType,
    };
  } catch (error: any) {
    console.error('Failed to generate preview URL:', error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Failed to generate preview URL',
    });
  }
});
