using System;
using BO.AppServer.Metadata.Configuration;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Quadarax.Foundation.Core.Data.Extensions;

namespace BO.AppServer.Web.Data
{
    public class IFDbContext : IdentityDbContext
    {
        private readonly string _connectionString;
        private readonly ILogger _logger;

        public IFDbContext(DbContextOptions options, IOptions<Configuration> config, ILoggerFactory logger)
            : base(options)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));
            _connectionString = config.Value.System.DbConnectionIF;
            if (logger == null)
                throw new ArgumentNullException(nameof(logger));
            _logger = logger.CreateLogger<IFDbContext>();
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                var cs = new ConnectionStringHelper(_connectionString);
                _logger.Log(LogLevel.Information, $"Connecting to database '{cs}' ...");
                optionsBuilder.UseSqlServer(_connectionString);
            }
        }
    }
}
