using e_suite.API.Common.repository;
using e_suite.Database.Audit;
using e_suite.Database.Core;
using e_suite.Database.Core.Extensions;
using e_suite.Database.Core.Tables.Domain;
using eSuite.Core.Miscellaneous;
using Microsoft.EntityFrameworkCore;

namespace e_suite.Modules.DomainManager.Repository;

public class DomainRepository : RepositoryBase, IDomainRepository
{
    public DomainRepository(IEsuiteDatabaseDbContext databaseDbContext) : base(databaseDbContext)
    {
    }

    public IQueryable<Domain> GetDomains()
    {
        return DatabaseDbContext.Domains.Where(x => !x.Deleted);
    }

    public async Task<Domain?> GetDomainById(IGeneralIdRef generalIdRef, CancellationToken cancellationToken)
    {
        return await DatabaseDbContext.Domains
            .Include(nameof(Domain.SsoProvider))
            .FindByGeneralIdRefAsync(generalIdRef, cancellationToken);
    }

    public async Task<Domain?> GetDomainByName(string domainName, CancellationToken cancellationToken)
    {
        return await DatabaseDbContext.Domains.SingleOrDefaultAsync(x => x.Name == domainName, cancellationToken);
    }

    public async Task EditDomainAsync(AuditUserDetails auditUserDetails, Domain domain, CancellationToken cancellationToken)
    {
        DatabaseDbContext.Domains.Update(domain);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }

    public async Task CreateDomainAsync(AuditUserDetails auditUserDetails, Domain domain, CancellationToken cancellationToken)
    {
        await DatabaseDbContext.Domains.AddAsync(domain, cancellationToken);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }

    public async Task AddAdministratorRoleAsync(AuditUserDetails auditUserDetails, Domain domain, CancellationToken cancellationToken)
    {
        var administratorRole = new Role
        {
            Name = "Administrators",
            Domain = domain,
            IsSuperUser = false,
            IsAdministrator = true,
            CanDelete = false,
            Deleted = false,
            Guid = Guid.NewGuid(),
        };

        await DatabaseDbContext.Roles.AddAsync(administratorRole, cancellationToken);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }
}