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

namespace CMSMicroservice.Application.UserAddressCQ.Queries.GetCustomerAddresses;

public class GetCustomerAddressesQueryHandler : IRequestHandler<GetCustomerAddressesQuery, GetCustomerAddressesQueryResponse>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

    public async Task<GetCustomerAddressesQueryResponse> Handle(GetCustomerAddressesQuery 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");
        }

        // Get all addresses for the current user
        var addresses = await _context.UserAddresses
            .Where(ua => ua.UserId == userId && !ua.IsDeleted)
            .OrderByDescending(ua => ua.IsDefault)
            .ThenByDescending(ua => ua.Created)
            .ToListAsync(cancellationToken);

        var response = new GetCustomerAddressesQueryResponse();

        foreach (var addr in addresses)
        {
            response.Addresses.Add(new CustomerAddressModel
            {
                Id = addr.Id,
                Title = addr.Title,
                Address = addr.Address,
                PostalCode = addr.PostalCode,
                IsDefault = addr.IsDefault,
                CityId = addr.CityId,
                CityName = string.Empty, // Will be populated by FrontOffice from City service
                ProvinceName = string.Empty // Will be populated by FrontOffice from City service
            });
        }

        return response;
    }
}
