using ColaFlow.Modules.Identity.Application.Dtos;
using ColaFlow.Modules.Identity.Domain.Aggregates.Tenants;
using ColaFlow.Modules.Identity.Domain.Repositories;
using MediatR;

namespace ColaFlow.Modules.Identity.Application.Queries.GetTenantBySlug;

public class GetTenantBySlugQueryHandler(ITenantRepository tenantRepository)
    : IRequestHandler<GetTenantBySlugQuery, TenantDto?>
{
    public async Task<TenantDto?> Handle(GetTenantBySlugQuery request, CancellationToken cancellationToken)
    {
        var slug = TenantSlug.Create(request.Slug);
        var tenant = await tenantRepository.GetBySlugAsync(slug, cancellationToken);

        if (tenant == null)
            return null;

        return new TenantDto
        {
            Id = tenant.Id,
            Name = tenant.Name.Value,
            Slug = tenant.Slug.Value,
            Status = tenant.Status.ToString(),
            Plan = tenant.Plan.ToString(),
            SsoEnabled = tenant.SsoConfig != null,
            SsoProvider = tenant.SsoConfig?.Provider.ToString(),
            CreatedAt = tenant.CreatedAt,
            UpdatedAt = tenant.UpdatedAt ?? tenant.CreatedAt
        };
    }
}
