using e_suite.API.Common.models;
using e_suite.API.Common.repository;
using e_suite.Database.Audit.Tables.Audit;
using e_suite.Database.Core;
using Microsoft.EntityFrameworkCore;

namespace e_suite.Modules.AuditLog.repository;

public class AuditLogRepository : RepositoryBase, IAuditLogRepository
{
    public AuditLogRepository(IEsuiteDatabaseDbContext databaseDbContext) : base(databaseDbContext)
    {
    }

    public IQueryable<AuditEntry> GetAuditEntries(AuditParams? auditParams, bool primaryOnly)
    {
        IQueryable<AuditEntry> queryable = DatabaseDbContext.AuditEntries
            .Include(ae_view => ae_view.AuditLog);

        if (primaryOnly)
        {
            queryable = queryable
                .Where(ae_view => ae_view.IsPrimary);
        }
        
        if (auditParams != null)
        {
            return queryable.Join(DatabaseDbContext.AuditEntries
                    .Where(ae_lookup => ae_lookup.EntityName == auditParams.EntityName &&
                                        ae_lookup.PrimaryKey == auditParams.PrimaryKey),
                ae_lookup => ae_lookup.AuditLogId,
                ae_view => ae_view.AuditLogId,
                (ae_lookup, ae_view) => ae_lookup);
        }

        return queryable;
    }
}