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.SiteManager.repository;

public class SiteManagerRepository : RepositoryBase, ISiteManagerRepository
{
    public SiteManagerRepository(IEsuiteDatabaseDbContext databaseDbContext) : base(databaseDbContext)
    {
    }

    public IQueryable<Site> GetSites()
    {
        return DatabaseDbContext.Sites
            .Include( x=> x.Organisation)
            .Where(x => x.Deleted == false);
    }

    public async Task<Site?> GetSite(IGeneralIdRef generalIdRef, CancellationToken cancellationToken)
    {
        return await GetSites().FindByGeneralIdRefAsync(generalIdRef, cancellationToken);
    }

    public async Task<Site?> GetSite(long sigmaId, CancellationToken cancellationToken)
    {
        return await GetSites().SingleOrDefaultAsync(x => x.SigmaId == sigmaId, cancellationToken);
    }

    public async Task EditSite(AuditUserDetails auditUserDetails, Site editedSite, CancellationToken cancellationToken)
    {
        DatabaseDbContext.Sites.Update(editedSite);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }

    public async Task CreateSite(AuditUserDetails auditUserDetails, Site newSite, CancellationToken cancellationToken)
    {
        var newSites = new List<Site>
        {
            newSite
        };

        await CreateSite(auditUserDetails, newSites, cancellationToken);
    }

    public async Task CreateSite(AuditUserDetails auditUserDetails, IEnumerable<Site> newSites, CancellationToken cancellationToken)
    {
        foreach (var newSite in newSites)
        {
            DatabaseDbContext.Sites.Add(newSite);
        }

        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }
}