// 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 ILogger<CreateShopCommandHandler> _logger;

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

    public async Task<CreateShopResult> Handle(CreateShopCommand request, CancellationToken cancellationToken)
    {
        // EN: Use user ID passed from the controller
        // VI: Dùng user ID được truyền từ controller
        var userId = request.UserId;

        // 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 (compare StatusId since Status navigation is not loaded by EF)
        // VI: Kiểm tra merchant có active không (compare StatusId vì Status navigation không được load bởi EF)
        if (merchant.StatusId != MerchantStatus.Active.Id)
        {
            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ề
        // EN: Parse business category (includes vertical-specific aliases)
        // VI: Parse ngành nghề (bao gồm alias theo ngành hàng)
        var category = request.Category.ToLowerInvariant() switch
        {
            "foodbeverage" => BusinessCategory.FoodBeverage,
            "cafe" or "café" or "coffee" => BusinessCategory.Cafe,
            "restaurant" or "nhà hàng" or "bar" => BusinessCategory.Restaurant,
            "karaoke" => BusinessCategory.Karaoke,
            "spa" or "massage" or "wellness" => BusinessCategory.Spa,
            "fashion" => BusinessCategory.Fashion,
            "electronics" => BusinessCategory.Electronics,
            "healthcare" => BusinessCategory.Healthcare,
            "beauty" or "salon" or "thẩm mỹ" => 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,
            "Draft" // EN: New shops are always Draft / VI: Shop mới luôn là Draft
        );
    }
}
