using Dollet.Core.Entities;
using Microsoft.EntityFrameworkCore;

namespace Dollet.Infrastructure.DAL
{
    public class DolletDbContext : DbContext
    {
        public DbSet<AppData> AppData { get; set; }
        public DbSet<Account> Accounts { get; set; }
        public DbSet<Expense> Expenses { get; set; }
        public DbSet<Income> Incomes { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Currency> Currencies { get; set; }
        public DbSet<CurrencyValue> CurrencyValues { get; set; }

        public DolletDbContext(DbContextOptions options) : base(options)
        {
            Database.EnsureCreated();
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Account>()
                .HasMany(x => x.Expenses)
                .WithOne(x => x.Account)
                .OnDelete(DeleteBehavior.SetNull);

            modelBuilder.Entity<Account>()
                .HasMany(x => x.Incomes)
                .WithOne(x => x.Account)
                .OnDelete(DeleteBehavior.SetNull);

            modelBuilder.Entity<Expense>()
                .HasOne(x => x.Account)
                .WithMany(x => x.Expenses)
                .OnDelete(DeleteBehavior.SetNull);

            modelBuilder.Entity<Income>()
                .HasOne(x => x.Account)
                .WithMany(x => x.Incomes)
                .OnDelete(DeleteBehavior.SetNull);

            base.OnModelCreating(modelBuilder);
        }
    }
}
