# @bernierllc/file-handler

Unified file operations and storage abstraction for @bernierllc packages. This core package provides a clean interface for file upload, download, processing, and validation across multiple storage backends.

## Installation

```bash
npm install @bernierllc/file-handler
```

## Usage

```typescript
import { FileHandler, FileData } from '@bernierllc/file-handler';

// Initialize with configuration
const fileHandler = new FileHandler({
  storage: {
    type: 'supabase', // or 'auto', 's3', 'azure', 'gcp', 'local'
    fallbackTo: ['local']
  },
  processing: {
    imageOptimization: true,
    validation: true,
    maxFileSize: '10MB',
    allowedTypes: ['image/*', 'application/pdf']
  }
});

// Initialize the handler
await fileHandler.initialize();

// Upload a file
const fileData: FileData = {
  buffer: fileBuffer,
  filename: 'example.jpg',
  contentType: 'image/jpeg',
  size: fileBuffer.length
};

const uploadResult = await fileHandler.uploadFile(fileData, {
  path: 'uploads',
  public: true
});

if (uploadResult.success) {
  console.log('File uploaded:', uploadResult.data.fileId);
}

// Download a file
const downloadResult = await fileHandler.downloadFile(fileId);
if (downloadResult.success) {
  console.log('Downloaded file:', downloadResult.data.filename);
}

// Process an image
const processResult = await fileHandler.processImage(imageBuffer, {
  resize: { width: 800, height: 600 },
  format: 'webp',
  quality: 85
});

// Validate a file
const validation = await fileHandler.validateFile(fileData, {
  maxSize: 5 * 1024 * 1024, // 5MB
  allowedTypes: ['image/*'],
  allowedExtensions: ['jpg', 'png', 'webp']
});
```

## API Reference

### FileHandler

Main class providing unified file operations.

#### Constructor

```typescript
new FileHandler(config?: FileHandlerConfig)
```

#### Methods

- `initialize(): Promise<FileOperationResult<void>>` - Initialize the file handler
- `uploadFile(file: FileData, options?: UploadOptions): Promise<FileOperationResult<UploadResult>>` - Upload a file
- `downloadFile(fileId: string, options?: DownloadOptions): Promise<FileOperationResult<FileData>>` - Download a file
- `deleteFile(fileId: string): Promise<FileOperationResult<DeleteResult>>` - Delete a file
- `listFiles(options?: ListOptions): Promise<FileOperationResult<FileList>>` - List files
- `getFileMetadata(fileId: string): Promise<FileOperationResult<FileMetadata>>` - Get file metadata
- `getFileUrl(fileId: string, expiresIn?: number): Promise<FileOperationResult<string>>` - Get file URL
- `processImage(buffer: Buffer, options: ImageProcessOptions): Promise<FileOperationResult<Buffer>>` - Process an image
- `validateFile(file: FileData, rules?: ValidationRules): Promise<ValidationResult>` - Validate a file
- `scanForVirus(buffer: Buffer): Promise<ScanResult>` - Scan file for viruses (placeholder)

### Storage Backends

#### Supported Backends

- **Supabase Storage** - Full implementation with upload, download, delete, list operations
- **Local Storage** - Planned (not implemented)
- **AWS S3** - Planned (not implemented) 
- **Azure Blob Storage** - Planned (not implemented)
- **Google Cloud Storage** - Planned (not implemented)

#### Backend Selection

```typescript
{
  storage: {
    type: 'auto', // Auto-select best available backend
    fallbackTo: ['supabase', 'local'] // Fallback order
  }
}
```

### Image Processing

Powered by Sharp for high-performance image transformations:

```typescript
const processed = await ImageProcessor.processImage(buffer, {
  resize: { width: 800, height: 600, fit: 'cover' },
  format: 'webp',
  quality: 85,
  blur: 2,
  sharpen: 1,
  rotate: 90,
  flip: 'horizontal'
});
```

### File Validation

Comprehensive security and constraint validation:

```typescript
const validation = await FileValidator.validateFile(file, {
  maxSize: 10 * 1024 * 1024, // 10MB
  allowedTypes: ['image/*', 'application/pdf'],
  allowedExtensions: ['jpg', 'png', 'pdf'],
  maxDimensions: { width: 2000, height: 2000 }
});
```

#### Security Features

- Executable file detection and blocking
- Directory traversal protection
- Suspicious filename pattern detection
- File type validation with MIME type checking
- Size limit enforcement

## Configuration

### Environment Variables

For Supabase backend:

```bash
SUPABASE_URL=your_supabase_url
SUPABASE_ANON_KEY=your_supabase_anon_key  
SUPABASE_BUCKET_NAME=uploads
```

### FileHandlerConfig

```typescript
interface FileHandlerConfig {
  storage?: {
    type: 'auto' | 'local' | 's3' | 'azure' | 'gcp' | 'supabase';
    fallbackTo?: string[];
  };
  processing?: {
    imageOptimization?: boolean;
    virusScanning?: boolean;
    validation?: boolean;
    maxFileSize?: string;
    allowedTypes?: string[];
  };
}
```

## Error Handling

All operations return `FileOperationResult<T>` with structured error handling:

```typescript
interface FileOperationResult<T = void> {
  success: boolean;
  data?: T;
  error?: string;
}
```

## See Also

- [@bernierllc/retry-policy](../retry-policy) - Used for upload retry logic
- [@bernierllc/csv-parser](../csv-parser) - CSV file processing  
- [@bernierllc/markdown-renderer](../markdown-renderer) - Markdown file processing

## License

Copyright (c) 2025 Bernier LLC. All rights reserved.