using Butter.Types;
using Lactose.Context;
using Lactose.Models;
using Microsoft.AspNetCore.Identity;

namespace Lactose.Services;

interface IDbInitializer {
    void Initialize();
}

class DbInitializer(
    LactoseDbContext dbContext,
    IPasswordHasher<User> passwordHasher
    ): IDbInitializer
{
    public void Initialize() {
        ArgumentNullException.ThrowIfNull(dbContext, nameof(dbContext));

        var task = dbContext.Database.GetPendingMigrationsAsync();

        task.ContinueWith(
            (r) => {
                if (r.Result.Any()) dbContext.Database.Migrate();
            }
        ).Wait();
        // if(dbContext.Database.GetPendingMigrations().Any()) // Timeoout
        if (dbContext.Users.Any()) return;
        var user = new User {
            Username    = "admin",
            Email       = "admin@admin.com",
            AccessLevel = EAccessLevel.Admin,
            CreatedAt   = DateTime.Now,
            UpdatedAt   = DateTime.Now
        };
        user.Password = passwordHasher.HashPassword(user, "admin");
        dbContext.Users.Add(user);
        dbContext.SaveChanges();
    }
}