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

namespace e_suite.Modules.CustomFieldsManager.Repository;

public class CustomFieldRepository : RepositoryBase, ICustomFieldRepository
{
#pragma warning disable IDE0290
    public CustomFieldRepository(IEsuiteDatabaseDbContext databaseDbContext) : base(databaseDbContext)
    {
    }
#pragma warning restore IDE0290

    public async Task CreateAsync(AuditUserDetails auditUserDetails, CustomField customField, CancellationToken cancellationToken)
    {
        await DatabaseDbContext.CustomFields.AddAsync(customField, cancellationToken);

        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }

    public IQueryable<CustomField> GetCustomFieldList()
    {
        return DatabaseDbContext.CustomFields.Where(x => !x.Deleted);
    }

    public async Task<CustomField?> GetByIdAsync(IGeneralIdRef id, CancellationToken cancellationToken)
    {
        var res = await DatabaseDbContext.CustomFields.FindByGeneralIdRefAsync(id, cancellationToken);
        return res;
    }

    public async Task<CustomField?> GetByNameAsync(string name, CancellationToken cancellationToken)
        => await DatabaseDbContext.CustomFields.FirstOrDefaultAsync(cf => cf.Name == name && cf.Deleted == false, cancellationToken);


    public async Task EditAsync(AuditUserDetails auditUserDetails, CustomField customField, CancellationToken cancellationToken)
    {
        DatabaseDbContext.CustomFields.Update(customField);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }
}
