namespace TaxBaik.Application.Services;

using System.Text.RegularExpressions;
using TaxBaik.Domain.Entities;
using TaxBaik.Domain.Interfaces;

public class CategoryService(ICategoryRepository repository)
{
    public async Task<IEnumerable<Category>> GetAllAsync(CancellationToken ct = default) =>
        await repository.GetAllAsync(ct);

    public async Task<Category?> GetBySlugAsync(string slug, CancellationToken ct = default) =>
        await repository.GetBySlugAsync(slug, ct);

    public async Task<Category?> GetByIdAsync(int id, CancellationToken ct = default) =>
        await repository.GetByIdAsync(id, ct);

    public async Task<Category> CreateAsync(string name, string? description, CancellationToken ct = default)
    {
        var slug = GenerateSlug(name);
        var category = new Category
        {
            Name = name.Trim(),
            Slug = slug,
            SortOrder = 0
        };

        var id = await repository.CreateAsync(category, ct);
        return new Category { Id = id, Name = category.Name, Slug = category.Slug, SortOrder = category.SortOrder };
    }

    public async Task<Category?> UpdateAsync(int id, string name, string? description, CancellationToken ct = default)
    {
        var category = await repository.GetByIdAsync(id, ct);
        if (category == null)
            return null;

        category.Name = name.Trim();
        category.Slug = GenerateSlug(name);
        await repository.UpdateAsync(category, ct);
        return category;
    }

    public async Task DeleteAsync(int id, CancellationToken ct = default) =>
        await repository.DeleteAsync(id, ct);

    private static string GenerateSlug(string name)
    {
        var slug = Regex.Replace(name.ToLowerInvariant(), @"[^\w\s-]", "");
        slug = Regex.Replace(slug, @"\s+", "-");
        slug = Regex.Replace(slug, @"-+", "-").Trim('-');
        return slug.Length > 100 ? slug[..100] : slug;
    }
}
