using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

namespace Kynareth.Models;

public class KynarethDbContext : DbContext
{
	public DbSet<ApiCall> Calls { get; set; }
	public DbSet<ApiToken> Tokens { get; set; }

	public KynarethDbContext() : base()
	{
		ChangeTracker.LazyLoadingEnabled = true;
	}
	
	public KynarethDbContext(DbContextOptions<KynarethDbContext> options) : base(options)
	{
		ChangeTracker.LazyLoadingEnabled = true;
	}
	
	protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
	{
		configurationBuilder
			.Properties<DateTime>()
			.HaveConversion<DateTimeToUtcConverter>();
	}
}

/// <summary>
/// Deserializes DateTime so if its Kind is Unspecified then it's set to Utc. 
/// Does nothing on Serialization as SQL Server discards this info when saving to DateTime fields. 
/// </summary>
public class DateTimeToUtcConverter : ValueConverter<DateTime, DateTime>
{
	public DateTimeToUtcConverter() : base(Serialize, Deserialize, null)
	{
	}

	static Expression<Func<DateTime, DateTime>> Deserialize = 
		x => x.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(x, DateTimeKind.Utc) : x;
	static Expression<Func<DateTime, DateTime>> Serialize = x => x;
}