using e_suite.API.Common.repository;
using e_suite.Database.Audit;
using e_suite.Database.Core;
using e_suite.Database.Core.Tables.Mail;
using eSuite.Core.MailService;
using Microsoft.EntityFrameworkCore;

namespace e_suite.Modules.MailTemplatesManager.repository;

public class MailTemplatesManagerRepository : RepositoryBase, IMailTemplatesManagerRepository
{
    public MailTemplatesManagerRepository(IEsuiteDatabaseDbContext databaseDbContext) : base(databaseDbContext)
    {
    }

    public async Task<MailTemplate?> GetMailTemplate(long domainId, MailType emailRequestEmailType, CancellationToken cancellationToken)
    {
        return await DatabaseDbContext.MailTemplates.SingleOrDefaultAsync(x =>
            !x.Deleted && x.DomainId == domainId && x.MailType == emailRequestEmailType, cancellationToken);
    }

    public async Task InsertMailTemplateAsync(MailTemplate template, AuditUserDetails auditUserDetails,
        CancellationToken cancellationToken)
    {
        await DatabaseDbContext.MailTemplates.AddAsync(template);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }

    public async Task UpdateMailTemplateAsync(MailTemplate template, AuditUserDetails auditUserDetails,
        CancellationToken cancellationToken)
    {
        DatabaseDbContext.MailTemplates.Update(template);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }
}