// EN: Handler for CreateShopCommand.
// VI: Handler cho CreateShopCommand.

using MediatR;
using MerchantService.Domain.AggregatesModel.MerchantAggregate;
using MerchantService.Domain.AggregatesModel.ShopAggregate;
using MerchantService.Domain.Exceptions;

namespace MerchantService.API.Application.Commands.Shops;

/// <summary>
/// EN: Handler for creating a new shop.
/// VI: Handler để tạo shop mới.
/// </summary>
public class CreateShopCommandHandler : IRequestHandler<CreateShopCommand, CreateShopResult>
{
    private readonly IMerchantRepository _merchantRepository;
    private readonly IShopRepository _shopRepository;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly ILogger<CreateShopCommandHandler> _logger;

    public CreateShopCommandHandler(
        IMerchantRepository merchantRepository,
        IShopRepository shopRepository,
        IHttpContextAccessor httpContextAccessor,
        ILogger<CreateShopCommandHandler> logger)
    {
        _merchantRepository = merchantRepository;
        _shopRepository = shopRepository;
        _httpContextAccessor = httpContextAccessor;
        _logger = logger;
    }

    public async Task<CreateShopResult> Handle(CreateShopCommand request, CancellationToken cancellationToken)
    {
        // EN: Get current user ID from claims
        // VI: Lấy user ID hiện tại từ claims
        var userIdClaim = _httpContextAccessor.HttpContext?.User.FindFirst("sub")?.Value
            ?? _httpContextAccessor.HttpContext?.User.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;
        
        if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
        {
            throw new DomainException("User not authenticated");
        }

        // EN: Get merchant by user ID
        // VI: Lấy merchant theo user ID
        var merchant = await _merchantRepository.GetByUserIdAsync(userId, cancellationToken);
        if (merchant == null)
        {
            throw new DomainException("Merchant not found. Please register as a merchant first.");
        }

        // EN: Check if merchant is active
        // VI: Kiểm tra merchant có active không
        if (merchant.Status != MerchantStatus.Active)
        {
            throw new DomainException("Only active merchants can create shops. Please wait for approval.");
        }

        // EN: Check if slug already exists
        // VI: Kiểm tra slug đã tồn tại chưa
        var slugExists = await _shopRepository.SlugExistsAsync(request.Slug, cancellationToken);
        if (slugExists)
        {
            throw new DomainException($"Shop slug '{request.Slug}' is already taken");
        }

        // EN: Parse shop type
        // VI: Parse loại shop
        var shopType = request.Type.ToLowerInvariant() switch
        {
            "onlineonly" => ShopType.OnlineOnly,
            "physicalonly" => ShopType.PhysicalOnly,
            "hybrid" => ShopType.Hybrid,
            _ => ShopType.Hybrid
        };

        // EN: Parse business category
        // VI: Parse ngành nghề
        var category = request.Category.ToLowerInvariant() switch
        {
            "foodbeverage" => BusinessCategory.FoodBeverage,
            "fashion" => BusinessCategory.Fashion,
            "electronics" => BusinessCategory.Electronics,
            "healthcare" => BusinessCategory.Healthcare,
            "beauty" => BusinessCategory.Beauty,
            "education" => BusinessCategory.Education,
            "entertainment" => BusinessCategory.Entertainment,
            "services" => BusinessCategory.Services,
            "grocery" => BusinessCategory.Grocery,
            "homefurniture" => BusinessCategory.HomeFurniture,
            _ => BusinessCategory.Other
        };

        // EN: Create shop
        // VI: Tạo shop
        var shop = new Shop(merchant.Id, request.Name, request.Slug, shopType, category);

        // EN: Update description if provided
        // VI: Cập nhật mô tả nếu có
        if (!string.IsNullOrWhiteSpace(request.Description))
        {
            shop.UpdateInfo(request.Name, request.Description);
        }

        // EN: Update contact info if provided
        // VI: Cập nhật thông tin liên hệ nếu có
        if (!string.IsNullOrWhiteSpace(request.Phone) || 
            !string.IsNullOrWhiteSpace(request.Email))
        {
            shop.UpdateContactInfo(new ContactInfo
            {
                Phone = request.Phone ?? string.Empty,
                Email = request.Email,
                Website = request.Website
            });
        }

        // EN: Save shop
        // VI: Lưu shop
        _shopRepository.Add(shop);
        await _shopRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation(
            "Shop created: {ShopId} by merchant {MerchantId}",
            shop.Id, merchant.Id);

        return new CreateShopResult(
            shop.Id,
            shop.Name,
            shop.Slug,
            shop.Status.Name
        );
    }
}
