using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudDb
{
    public static class EFExtensionsExceptionHandling
    {
        public static async Task<int> SaveChangesWithExceptionHandling(this IAsbCloudDbContext db, CancellationToken token)
        {
            try
            {
                var result = await db.SaveChangesAsync(token);
                return result;
            }
            catch (DbUpdateException ex)
            {
                if (ex.InnerException is PostgresException pgException)
                    TryConvertPostgresExceptionToValidateException(pgException);
                throw;
            }
        }

        private static void TryConvertPostgresExceptionToValidateException(PostgresException pgException)
        {
            if (pgException.SqlState == PostgresErrorCodes.ForeignKeyViolation)
                // TODO: replace ArgumentException by new Exception
                throw new ArgumentException(pgException.Message + "\r\n" + pgException.Detail, "dtos");
        }
    }
}