using MemberCenter.Application.Abstractions;
using MemberCenter.Application.Models.Admin;
using MemberCenter.Domain.Entities;
using MemberCenter.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;

namespace MemberCenter.Infrastructure.Services;

public sealed class SecuritySettingsService : ISecuritySettingsService
{
    private const string AccessTokenKey = "token_access_minutes";
    private const string RefreshTokenKey = "token_refresh_days";

    private readonly MemberCenterDbContext _dbContext;

    public SecuritySettingsService(MemberCenterDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<SecuritySettingsDto> GetAsync()
    {
        var access = await GetFlagAsync(AccessTokenKey, 60);
        var refresh = await GetFlagAsync(RefreshTokenKey, 30);
        return new SecuritySettingsDto(access, refresh);
    }

    public async Task SaveAsync(SecuritySettingsDto settings)
    {
        await SetFlagAsync(AccessTokenKey, settings.AccessTokenMinutes.ToString());
        await SetFlagAsync(RefreshTokenKey, settings.RefreshTokenDays.ToString());
        await _dbContext.SaveChangesAsync();
    }

    private async Task<int> GetFlagAsync(string key, int defaultValue)
    {
        var flag = await _dbContext.SystemFlags.FirstOrDefaultAsync(f => f.Key == key);
        if (flag is null)
        {
            return defaultValue;
        }

        return int.TryParse(flag.Value, out var value) ? value : defaultValue;
    }

    private async Task SetFlagAsync(string key, string value)
    {
        var flag = await _dbContext.SystemFlags.FirstOrDefaultAsync(f => f.Key == key);
        if (flag is null)
        {
            _dbContext.SystemFlags.Add(new SystemFlag
            {
                Id = Guid.NewGuid(),
                Key = key,
                Value = value,
                UpdatedAt = DateTimeOffset.UtcNow
            });
        }
        else
        {
            flag.Value = value;
            flag.UpdatedAt = DateTimeOffset.UtcNow;
        }
    }
}
