using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.UserAddressCQ.Commands.SetCustomerDefaultAddress;

public class SetCustomerDefaultAddressCommandHandler : IRequestHandler<SetCustomerDefaultAddressCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

    public async Task<Unit> Handle(SetCustomerDefaultAddressCommand request, CancellationToken cancellationToken)
    {
        // Extract UserId from JWT token
        var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
        if (userId == 0)
        {
            throw new UnauthorizedAccessException("User not authenticated");
        }

        // Find address and verify ownership
        var address = await _context.UserAddresses
            .FirstOrDefaultAsync(ua => ua.Id == request.Id && ua.UserId == userId && !ua.IsDeleted, cancellationToken);

        if (address == null)
        {
            throw new Exception("آدرس یافت نشد یا به شما تعلق ندارد");
        }

        // Unset all other defaults for this user
        var existingDefaults = await _context.UserAddresses
            .Where(ua => ua.UserId == userId && ua.IsDefault && ua.Id != request.Id && !ua.IsDeleted)
            .ToListAsync(cancellationToken);

        foreach (var addr in existingDefaults)
        {
            addr.IsDefault = false;
        }

        // Set this address as default
        address.IsDefault = true;
        address.LastModified = DateTime.UtcNow;

        _context.UserAddresses.Update(address);
        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
