using Microsoft.EntityFrameworkCore;
using ms_useCaseService.Database;
using ms_useCaseService.Database.Models;
using webApiGateway.Objects.Objects;

namespace ms_useCaseService.Mapping;

/// <summary>
/// Provides method for inserting data into the database.
/// </summary>
public class Insert
{
    /// <summary>
    /// Represents the logger instance for this class.
    /// </summary>
    private static ILogger Logger = Logging.LoggerFactory.CreateLogger<Insert>();

    /// <summary>
    /// Inserts data into the database.
    /// </summary>
    /// <param name="title">The title of the rule.</param>
    /// <param name="description">The description of the rule.</param>
    /// <param name="tags">The tags associated with the rule.</param>
    /// <param name="logsource">The log source of the rule.</param>
    /// <exception cref="System.Exception">Thrown if an error occurs while saving the data to the database.</exception>
    public static void InsertData(string title, string description, string tags, string logsource)
    {    
        try
        {
            //Initializing database connection
            var configuration = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();
            var optionsBuilder = new DbContextOptionsBuilder<RulesContext>().UseNpgsql(configuration.GetConnectionString("Database"));
            var context = new RulesContext(optionsBuilder.Options);

            //Creating instances of Models classes to store them in the database
            var ruleType = new RuleType
            {
                Type = title,
                Description = description
            };
        
            var rulesMetadataType = new RulesMetadataType
            {
                Type = tags,
                LogSource = logsource
            };

            var rule = new Rule
            {
                RuleType = ruleType,
            };

            //Saving data into database
            context.RuleTypes.Add(ruleType);
            context.RulesMetadataTypes.Add(rulesMetadataType);
            context.Rules.Add(rule);
            context.SaveChanges();
            
            //Logging the data in the console
            Logger.LogInformation("Data successfully inserted - Title: {0}, Description: {1}, Tags: {2}, LogSource: {3}", title, description, tags, logsource);
        }
        catch(Exception ex)
        {
            Logger.LogError(ex.Message); 
        }
    }
}