using System.Data;
using System.Diagnostics;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;

namespace PlanTempus.Core.Database;

public class DatabaseScope : IDisposable
{
    internal readonly IOperationHolder<DependencyTelemetry> _operation;
    private readonly Stopwatch _stopwatch;

    public DatabaseScope(IDbConnection connection, IOperationHolder<DependencyTelemetry> operation)
    {
        Connection = connection;
        _operation = operation;
        _operation.Telemetry.Success = true;
        _operation.Telemetry.Timestamp = DateTimeOffset.UtcNow;
        _stopwatch = Stopwatch.StartNew();
    }

    public IDbConnection Connection { get; }

    public void Dispose()
    {
        _stopwatch.Stop();
        _operation.Telemetry.Duration = _stopwatch.Elapsed;

        _operation.Dispose();
        Connection.Dispose();
    }

    public void Error(Exception ex)
    {
        _operation.Telemetry.Success = false;
        _operation.Telemetry.Properties["Error"] = ex.Message;
    }
}