using Application.Abstractions.Cache;
using Application.Abstractions.Data;
using Application.Features.Config.Get;
using Microsoft.EntityFrameworkCore;

namespace Application.Helpers;

public static class AccountConfigLoader
{
    /// <summary>
    /// Redis 캐시 → MSSQL 폴백으로 AccountConfigDto를 로드합니다.
    /// </summary>
    public static async Task<Response.AccountConfigDto> GetAccountConfigAsync(
        ICacheService cache, IAppDbContext db, CancellationToken ct)
    {
        // 1. Redis 캐시에서 조회
        var config = await cache.GetAsync<Response>(CacheKeys.Config, ct);
        if (config is not null)
        {
            return config.Account;
        }

        // 2. MSSQL 폴백
        var entity = await db.Config.AsNoTracking()
            .OrderByDescending(x => x.ID)
            .FirstOrDefaultAsync(ct);

        if (entity is null)
        {
            // Config가 없으면 기본값 반환
            return new Response.AccountConfigDto();
        }

        return new Response.AccountConfigDto
        {
            IsRegisterBlock = entity.Account.IsRegisterBlock,
            IsRegisterEmailAuth = entity.Account.IsRegisterEmailAuth,
            PasswordMinLength = entity.Account.PasswordMinLength,
            PasswordUppercaseLength = entity.Account.PasswordUppercaseLength,
            PasswordNumbersLength = entity.Account.PasswordNumbersLength,
            PasswordSpecialcharsLength = entity.Account.PasswordSpecialcharsLength,
            DeniedEmailList = entity.Account.DeniedEmailList,
            DeniedNameList = entity.Account.DeniedNameList,
            ChangeEmailDay = entity.Account.ChangeEmailDay,
            ChangeNameDay = entity.Account.ChangeNameDay,
            ChangeSummaryDay = entity.Account.ChangeSummaryDay,
            ChangeIntroDay = entity.Account.ChangeIntroDay,
            ChangePasswordDay = entity.Account.ChangePasswordDay,
            IsLoginEmailVerifiedOnly = entity.Account.IsLoginEmailVerifiedOnly,
            MaxLoginTryCount = entity.Account.MaxLoginTryCount,
            MaxLoginTryLimitSecond = entity.Account.MaxLoginTryLimitSecond
        };
    }
}
