using IWS5.Importer.Abstractions.Interfaces;
using Serilog.Context;

namespace IWS5.Importer.Worker.FileSystem;

public class FileHelper : IFileHelper
{
    private readonly Serilog.ILogger _logService;

    public FileHelper(Serilog.ILogger logService)
    {
        _logService = logService;
    }

    /// <summary>
    /// Ensures a directory exists; creates it if it does not exist.
    /// </summary>
    /// <param name="path">The directory path to ensure exists.</param>
    /// <param name="logContext">Context for logging purposes.</param>
    public void EnsureDirectoryExists(string directoryPath, string logContext)
    {
        if (Directory.Exists(directoryPath))
            return;

        try
        {
            Directory.CreateDirectory(directoryPath);
            using (LogContext.PushProperty("LogContext", nameof(FileHelper)))
                _logService.Information("Successfully created {LogContext} directory: {DirectoryPath}", logContext, directoryPath);
        }
        catch (Exception ex)
        {
            using (LogContext.PushProperty("LogContext", nameof(FileHelper)))
                _logService.Error(ex, "Critical error: Unable to create {LogContext} directory at {DirectoryPath}", logContext, directoryPath);
            throw new ApplicationException($"Failed to create directory: {directoryPath}", ex);
        }
    }

    /// <summary>
    /// Returns a unique directory path by appending a timestamp if the original path already exists.
    /// </summary>
    /// <param name="basePath">The original directory path.</param>
    /// <returns>A unique directory path.</param>
    public string GetUniqueDestinationPath(string basePath)
    {
        if (Directory.Exists(basePath))
        {
            return $"{basePath}_{GetTimestamp()}";
        }
        return basePath;
    }

    private static string GetTimestamp()
        => DateTime.UtcNow.ToString("yyyyMMddHHmmssfff");
}
