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

namespace e_suite.Modules.SequenceManager.Repository;

public class SequenceManagerRepository : RepositoryBase, ISequenceManagerRepository
{
    public SequenceManagerRepository(IEsuiteDatabaseDbContext databaseDbContext) : base(databaseDbContext)
    {
    }

    public async Task AddSequence(AuditUserDetails auditUserDetails, Sequence sequence, CancellationToken cancellationToken)
    {
        await DatabaseDbContext.Sequences.AddAsync(sequence, cancellationToken);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }

    public async Task<Sequence?> GetSequenceByName(string name, CancellationToken cancellationToken)
    {
        return await DatabaseDbContext.Sequences.Where(x => x.Name == name).FirstOrDefaultAsync(cancellationToken);
    }

    public async Task<Sequence?> GetSequenceById(IGeneralIdRef generalIdRef, CancellationToken cancellationToken)
    {
        return await DatabaseDbContext.Sequences.FindByGeneralIdRefAsync(generalIdRef, cancellationToken);
    }

    public async Task EditSequence(AuditUserDetails auditUserDetails, Sequence sequence, CancellationToken cancellationToken)
    {
        DatabaseDbContext.Sequences.Update(sequence);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }

    public IQueryable<Sequence> GetSequenceList()
    {
        return DatabaseDbContext.Sequences.Where(x => !x.Deleted);
    }
}