using System.Linq;
using System.Threading.Tasks;
using FAuth.DataBase.Tables;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;

namespace FAuth.DataBase
{
    /// <summary>
    /// 数据库数据初始化
    /// </summary>
    public static class DbContextInit
    {
        /// <summary>
        /// 是否首次执行
        /// </summary>
        private static bool _isFirstRun = true;

        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <param name="db">数据库上下文</param>
        /// <returns></returns>
        public static async Task InitSync(this FAuthDb db) {
            if(!_isFirstRun)
                return;
            _isFirstRun = false;
            db.Database.EnsureCreated();
            int appId = 0, rgId = 0, rId = 0, uId = 0;
            if(!db.Apps.Any()) {
                var nApp = new Apps {
                    Name = "FAuth",
                    Description = "Falcon统一登录认证服务器",
                };
                db.Entry(nApp).State = EntityState.Added;
                await db.SaveChangesAsync();
                appId = nApp.Id;
            }

            if(!db.RoleGroups.Any()) {
                var rg = new RoleGroup {
                    Name = "系统组",
                    Description = "系统相关角色组",
                };
                db.Entry(rg).State = EntityState.Added;
                await db.SaveChangesAsync();
                rgId = rg.Id;
            }

            if(appId != 0 && rgId != 0) {
                db.App_RoleGroups.Add(new App_RoleGroup {
                    AppId = appId,
                    RoleGroupId = rgId,
                });
                await db.SaveChangesAsync();
            }
            if(!db.Roles.Any()) {
                var nRole = new Roles {
                    Name = "Admin",
                    Description = "系统管理员",
                };
                db.Roles.Add(nRole);
                await db.SaveChangesAsync();
                rId = nRole.Id;
            }
            if(rgId != 0 && rId != 0) {
                db.RoleGroup_Roles.Add(new RoleGroup_Role {
                    RoleGroupId = rgId,
                    RoleId = rId,
                });
                await db.SaveChangesAsync();
            }
            if(!db.Users.Any()) {
                var nUser = new FUser {
                    Name = "系统管理员",
                    Password = "admin",
                    Status = 0,
                    UserName = "admin",
                };
                db.Users.Add(nUser);
                await db.SaveChangesAsync();
                uId = nUser.Id;
            }
            if(rId != 0 && uId != 0) {
                db.Role_Users.Add(new Role_User {
                    RoleId = rId,
                    UserId = uId,
                });
                await db.SaveChangesAsync();
            }
        }
    }
}
