import * as fs from 'fs';
import * as path from 'path';
import { promisify } from 'util';

const unlinkAsync = promisify(fs.unlink);

export class FileHandlerUtils {
    /**
     * Safely deletes a file with proper path resolution and error handling
     * @param filePath The file path to delete (can be relative or absolute)
     * @returns boolean indicating whether the file was successfully deleted
     */
    public static async deleteFile(filePath: string): Promise<boolean> {
        try {
            if (!filePath) {
                console.warn('FileHandlerUtils.deleteFile: filePath is required');
                return false;
            }

            // Resolve the absolute path properly
            let absolutePath: string;

            // If it's already an absolute path, use it as-is
            if (path.isAbsolute(filePath)) {
                absolutePath = filePath;
            } else {
                // If it starts with uploads, resolve from project root
                if (filePath.startsWith('uploads/')) {
                    // Use root-level uploads directory for both production and development
                    absolutePath = path.join(process.cwd(), filePath);
                } else {
                    // For relative paths, join with current working directory
                    absolutePath = path.join(process.cwd(), filePath);
                }
            }

            // Normalize the path (convert backslashes to forward slashes, resolve .. and .)
            absolutePath = path.normalize(absolutePath);

            // Check if file exists before attempting to delete
            if (!fs.existsSync(absolutePath)) {
                console.warn(`FileHandlerUtils.deleteFile: File does not exist at path: ${absolutePath}`);
                return false;
            }

            // Verify it's actually a file, not a directory
            const stats = fs.statSync(absolutePath);
            if (!stats.isFile()) {
                console.warn(`FileHandlerUtils.deleteFile: Path is not a file: ${absolutePath}`);
                return false;
            }

            // Attempt to delete the file
            await unlinkAsync(absolutePath);

            console.log(`FileHandlerUtils.deleteFile: Successfully deleted file: ${absolutePath}`);
            return true;
        } catch (error) {
            console.error(`FileHandlerUtils.deleteFile: Error deleting file ${filePath}:`, error);
            return false;
        }
    }

    /**
     * Checks if a file exists at the given path
     * @param filePath The file path to check
     * @returns boolean indicating whether the file exists
     */
    public static fileExists(filePath: string): boolean {
        if (!filePath) {
            return false;
        }

        let absolutePath: string;

        if (path.isAbsolute(filePath)) {
            absolutePath = filePath;
        } else if (filePath.startsWith('uploads/')) {
            // Use root-level uploads directory for both production and development
            absolutePath = path.join(process.cwd(), filePath);
        } else {
            absolutePath = path.join(process.cwd(), filePath);
        }

        absolutePath = path.normalize(absolutePath);

        return fs.existsSync(absolutePath) && fs.statSync(absolutePath).isFile();
    }

    /**
     * Gets the proper absolute path for a file based on environment
     * @param filePath The relative file path
     * @returns The resolved absolute path
     */
    public static getAbsolutePath(filePath: string): string {
        if (!filePath) {
            throw new Error('File path is required');
        }

        let absolutePath: string;

        if (path.isAbsolute(filePath)) {
            absolutePath = filePath;
        } else if (filePath.startsWith('uploads/')) {
            // Use root-level uploads directory for both production and development
            absolutePath = path.join(process.cwd(), filePath);
        } else {
            absolutePath = path.join(process.cwd(), filePath);
        }

        return path.normalize(absolutePath);
    }

    /**
     * Validates that a file path is within allowed directories to prevent directory traversal
     * @param filePath The file path to validate
     * @returns boolean indicating whether the path is valid
     */
    public static isValidFilePath(filePath: string): boolean {
        if (!filePath) {
            return false;
        }

        // Prevent directory traversal
        if (filePath.includes('../') || filePath.includes('..\\')) {
            return false;
        }

        // Normalize the path
        const normalizedPath = path.normalize(filePath);

        // Check if the path starts with allowed directories
        return normalizedPath.startsWith('uploads/') ||
            normalizedPath.startsWith(path.join(process.cwd(), 'uploads'));
    }
}