using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Merchants.Entities;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Infrastructure.App.Persistence;

namespace TakeoutSaaS.Infrastructure.App.Repositories;

/// <summary>
/// 商户类目的 EF Core 仓储实现。
/// </summary>
public sealed class EfMerchantCategoryRepository(TakeoutAppDbContext context)
    : IMerchantCategoryRepository
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<MerchantCategory>> ListAsync(long tenantId, CancellationToken cancellationToken = default)
    {
        var items = await context.MerchantCategories
            .AsNoTracking()
            .Where(x => x.TenantId == tenantId)
            .OrderBy(x => x.DisplayOrder)
            .ThenBy(x => x.CreatedAt)
            .ToListAsync(cancellationToken);

        return items;
    }

    /// <inheritdoc />
    public Task<bool> ExistsAsync(string name, long tenantId, CancellationToken cancellationToken = default)
    {
        return context.MerchantCategories.AnyAsync(
            x => x.TenantId == tenantId && x.Name == name, cancellationToken);
    }

    /// <inheritdoc />
    public Task<MerchantCategory?> FindByIdAsync(long id, long tenantId, CancellationToken cancellationToken = default)
    {
        return context.MerchantCategories
            .FirstOrDefaultAsync(x => x.TenantId == tenantId && x.Id == id, cancellationToken);
    }

    /// <inheritdoc />
    public Task AddAsync(MerchantCategory category, CancellationToken cancellationToken = default)
    {
        return context.MerchantCategories.AddAsync(category, cancellationToken).AsTask();
    }

    /// <inheritdoc />
    public Task RemoveAsync(MerchantCategory category, CancellationToken cancellationToken = default)
    {
        context.MerchantCategories.Remove(category);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task UpdateRangeAsync(IEnumerable<MerchantCategory> categories, CancellationToken cancellationToken = default)
    {
        context.MerchantCategories.UpdateRange(categories);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        return context.SaveChangesAsync(cancellationToken);
    }
}
