using CMSMicroservice.Application.Common.Interfaces;

namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerSettings;

public class GetCustomerSettingsQueryHandler : IRequestHandler<GetCustomerSettingsQuery, GetCustomerSettingsResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

    public GetCustomerSettingsQueryHandler(IApplicationDbContext context, ICurrentUserService currentUser)
    {
        _context = context;
        _currentUser = currentUser;
    }

    public async Task<GetCustomerSettingsResponseDto> Handle(GetCustomerSettingsQuery request, CancellationToken cancellationToken)
    {
        // Get userId from ICurrentUserService if not provided
        var userId = request.UserId == 0
            ? (long.TryParse(_currentUser.UserId, out var id) ? id : 0)
            : request.UserId;

        if (userId == 0)
            throw new UnauthorizedAccessException("User ID not found in JWT token");

        var user = await _context.Users
            .AsNoTracking()
            .Where(x => x.Id == userId)
            .FirstOrDefaultAsync(cancellationToken);

        if (user == null)
            throw new NotFoundException(nameof(User), userId);

        return new GetCustomerSettingsResponseDto
        {
            EmailNotifications = user.EmailNotifications,
            SmsNotifications = user.SmsNotifications,
            PushNotifications = user.PushNotifications,
            MarketingNotifications = false, // Not in User entity, default to false
            PreferredLanguage = "fa", // Default Persian
            TimeZone = "Asia/Tehran", // Default Iran timezone
            TwoFactorAuthEnabled = false // Not implemented yet
        };
    }
}
