using AyCode.Core.Server.Loggers;
using AyCode.Database.DbSets.Addresses;
using AyCode.Database.DbSets.Profiles;
using AyCode.Entities;
using AyCode.Interfaces.Addresses;
using AyCode.Interfaces.Profiles.Dtos;
using AyCode.Interfaces.Profiles;
using Microsoft.EntityFrameworkCore;
using AyCode.Interfaces.Addresses.Dtos;
using AyCode.Database.DbSets.Users;
using AyCode.Interfaces.Users;

namespace AyCode.Database.DbSets.Profiles;

public static class AcProfileDbSetExtensions
{
    public static TProfile? GetProfileById<TProfile>(this IAcProfileDbSetBase<TProfile> ctx, Guid profileId) where TProfile : class, IAcProfileDtoBase
        => ctx.Profiles.FirstOrDefault(u => u.Id == profileId);

    public static bool AddProfile<TProfile>(this IAcProfileDbSetBase<TProfile> ctx, TProfile profile) where TProfile : class, IAcProfileDtoBase
        => ctx.Profiles.Add(profile).State == EntityState.Added;

    public static bool UpdateProfile<TProfile>(this IAcProfileDbSetBase<TProfile> ctx, TProfile profile) where TProfile : class, IAcProfileDtoBase
        => ctx.Profiles.Update(profile).State == EntityState.Modified;

    private static bool RemoveProfile<TProfile, TAddress>(this IAcProfileDbSetBase<TProfile, TAddress> ctx, TProfile profile) 
        where TProfile : class, IAcProfile<TAddress>
        where TAddress : class, IAcAddressDtoBase
    {
        var address = ctx.GetAddressById(profile.AddressId);
        if (address != null) ctx.Addresses.Remove(address);

        return ctx.Profiles.Remove(profile).State == EntityState.Deleted;
    }

    public static bool RemoveProfile<TProfile, TAddress>(this IAcProfileDbSetBase<TProfile, TAddress> ctx, Guid profileId) 
        where TProfile : class, IAcProfile<TAddress>
        where TAddress : class, IAcAddressDtoBase
    {
        var profile = ctx.GetProfileById(profileId);

        return profile != null && ctx.RemoveProfile(profile);
    }
}