import * as fs from 'fs';
import * as path from 'path';

export class FileCleanupUtils {
    /**
     * Deletes all files in the specified directory
     * @param dirPath Path to the directory to clean up
     */
    public static async deleteAllFilesInDirectory(dirPath: string): Promise<void> {
        try {
            // Create directory if it doesn't exist
            if (!fs.existsSync(dirPath)) {
                fs.mkdirSync(dirPath, { recursive: true });
                console.log(`Directory created: ${dirPath}`);
                return;
            }

            // Read all files in the directory
            const files = fs.readdirSync(dirPath);

            if (files.length === 0) {
                console.log(`No files to delete in directory: ${dirPath}`);
                return;
            }

            // Delete each file
            for (const file of files) {
                const filePath = path.join(dirPath, file);
                const stats = fs.statSync(filePath);

                if (stats.isFile()) {
                    fs.unlinkSync(filePath);
                    console.log(`Deleted file: ${filePath}`);
                } else if (stats.isDirectory()) {
                    // If there are subdirectories, we can recursively delete them
                    await this.deleteAllFilesInDirectory(filePath);
                    // Remove the empty directory after its contents are deleted
                    fs.rmdirSync(filePath);
                    console.log(`Deleted directory: ${filePath}`);
                }
            }

            console.log(`Successfully cleaned up directory: ${dirPath}`);
        } catch (error) {
            console.error(`Error cleaning up directory ${dirPath}:`, error);
            throw error;
        }
    }

    /**
     * Cleans up the reports directory by deleting all PDF files
     */
    public static async cleanupReportsDirectory(): Promise<void> {
        // Use root-level uploads directory for both production and development
        const baseUploadsDir = path.join(process.cwd(), 'uploads');
        const reportsDir = path.join(baseUploadsDir, 'reports');

        try {
            // Create directory if it doesn't exist
            if (!fs.existsSync(reportsDir)) {
                fs.mkdirSync(reportsDir, { recursive: true });
                console.log(`Reports directory created: ${reportsDir}`);
                return;
            }

            // Read all files in the reports directory
            const files = fs.readdirSync(reportsDir);

            if (files.length === 0) {
                console.log('No files to delete in reports directory');
                return;
            }

            // Filter only PDF files and delete them
            const pdfFiles = files.filter(file =>
                file.toLowerCase().endsWith('.pdf')
            );

            if (pdfFiles.length === 0) {
                console.log('No PDF files found in reports directory');
                return;
            }

            // Delete each PDF file
            for (const file of pdfFiles) {
                const filePath = path.join(reportsDir, file);
                const stats = fs.statSync(filePath);

                if (stats.isFile()) {
                    fs.unlinkSync(filePath);
                    console.log(`Deleted PDF file: ${filePath}`);
                }
            }

            console.log(`Successfully cleaned up ${pdfFiles.length} PDF files from reports directory`);
        } catch (error) {
            console.error('Error cleaning up reports directory:', error);
            throw error;
        }
    }
}