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.Printer;
using eSuite.Core.Miscellaneous;
using Microsoft.EntityFrameworkCore;

namespace e_suite.Modules.OrganisationsManager.Repository;

public class OrganisationsManagerRepository : RepositoryBase, IOrganisationsManagerRepository
{
    public OrganisationsManagerRepository(IEsuiteDatabaseDbContext databaseDbContext) : base(databaseDbContext)
    {
    }

    public IQueryable<Organisation> GetOrganisationsList()
    {
        return DatabaseDbContext.Organisations.Where(x => x.Deleted == false);
    }

    public async Task<Organisation?> FindOrganisation(IGeneralIdRef generalIdRef, CancellationToken cancellationToken)
    {
        return await DatabaseDbContext.Organisations.FindByGeneralIdRefAsync(generalIdRef, cancellationToken);
    }

    public async Task AddOrganisation(AuditUserDetails auditUserDetails, Organisation organisation, CancellationToken cancellationToken)
    {
        await DatabaseDbContext.Organisations.AddAsync(organisation, cancellationToken);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }
        
    public async Task DeleteOrganisation(AuditUserDetails auditUserDetails, IGeneralIdRef generalIdRef, CancellationToken cancellationToken)
    {
        var organisation = await DatabaseDbContext.Organisations.FindByGeneralIdRefAsync(generalIdRef, cancellationToken);

        if (organisation != null)
        {
            organisation.Deleted = true;
            var sites = await DatabaseDbContext.Sites.Where(x => x.OrganisationId == organisation.Id).ToListAsync(cancellationToken);

            foreach (var site in sites)
            {
                site.Deleted = true;

                var specs = await DatabaseDbContext.Specifications.Where(x => x.SiteId == site.Id).ToListAsync(cancellationToken);
                specs.ForEach(x => x.Deleted = true);
            }
        }

        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }

    public async Task EditOrganisation(AuditUserDetails auditUserDetails, Organisation organisation, CancellationToken cancellationToken)
    {
        DatabaseDbContext.Organisations.Update(organisation);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }
}