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

namespace CMSMicroservice.Application.UserAddressCQ.Commands.CreateCustomerAddress;

public class CreateCustomerAddressCommandHandler : IRequestHandler<CreateCustomerAddressCommand, CreateCustomerAddressCommandResponse>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

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

        // If this address is set as default, unset other defaults
        if (request.IsDefault)
        {
            var existingDefaults = await _context.UserAddresses
                .Where(ua => ua.UserId == userId && ua.IsDefault && !ua.IsDeleted)
                .ToListAsync(cancellationToken);

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

        // Create new address
        var address = new UserAddress
        {
            UserId = userId,
            Title = request.Title,
            Address = request.Address,
            PostalCode = request.PostalCode,
            IsDefault = request.IsDefault,
            CityId = request.CityId,
            Created = DateTime.UtcNow
        };

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

        return new CreateCustomerAddressCommandResponse
        {
            Id = address.Id,
            Message = "آدرس با موفقیت ایجاد شد"
        };
    }
}
