using Microsoft.EntityFrameworkCore;
using Luticate2.Auth.DataAccess.Models;

namespace Luticate2.Auth.DataAccess
{
    public partial class LuDatabaseContext : DbContext
    {
        private readonly string _connectionString;

        public LuDatabaseContext()
        {
        }

        public LuDatabaseContext(string connectionString)
        {
            _connectionString = connectionString;
        }

        public LuDatabaseContext(DbContextOptions options) :base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (_connectionString != null) {
                optionsBuilder.UseNpgsql(_connectionString);
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            {% for table in dataSource.getTables() %}{% if (table.hasAny()) %}
            modelBuilder.Entity<{{ table.getName() }}>()
                .HasKey(c => new { {% for column in table.getPrimaryKeys() %}{% if (column.isSelected()) %}c.{{ column.getName() }}{% if not (loop.last) %}, {% endif %}{% endif %}{% endfor %} });
            {% for column in table.getColumns() %}{% if (column.isSelected()) and (column.hasDefaultValue()) %}
            modelBuilder.Entity<{{ table.getName() }}>()
                .Property(e => e.{{ column.getName() }})
                .HasDefaultValueSql("{{ column.getDefaultValueEscaped() }}");
            {% endif %}{% endfor %}
            {% for fk in table.getSourceForeignKeys() %}
            modelBuilder.Entity<{{ fk.getSourceTable().getName() }}>()
                .HasOne(e => e.{{ fk.getSourceForeignKeyName() }})
                .WithMany(e => e.{{ fk.getTargetForeignKeyName() }})
                .HasForeignKey("{% for column in fk.getSourceColumns() %}{{ column.getName }}{% if not (loop.last) %}, {% endif %}{% endfor %}")
                .HasConstraintName("{{ fk.getName() }}");
            {% endfor %}
            {% endif %}{% endfor %}
        }
        {% for table in dataSource.getTables() %}{% if (table.hasAny()) %}
        public virtual DbSet<{{ table.getName() }}> {{ table.getName() }} { get; set; }
        {% endif %}{% endfor %}
    }
}