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

namespace TakeoutSaaS.Infrastructure.App.Repositories;

/// <summary>
/// 租户套餐仓储实现。
/// </summary>
public sealed class EfTenantPackageRepository(TakeoutAppDbContext context) : ITenantPackageRepository
{
    /// <inheritdoc />
    public Task<TenantPackage?> FindByIdAsync(long id, CancellationToken cancellationToken = default)
    {
        return context.TenantPackages.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
    }

    /// <inheritdoc />
    public async Task<IReadOnlyList<TenantPackage>> SearchAsync(string? keyword, bool? isActive, CancellationToken cancellationToken = default)
    {
        // 1. 构建基础查询
        var query = context.TenantPackages.AsNoTracking();

        // 2. 关键字过滤
        if (!string.IsNullOrWhiteSpace(keyword))
        {
            var normalized = keyword.Trim();
            query = query.Where(x => EF.Functions.ILike(x.Name, $"%{normalized}%") || EF.Functions.ILike(x.Description ?? string.Empty, $"%{normalized}%"));
        }

        // 3. 状态过滤
        if (isActive.HasValue)
        {
            query = query.Where(x => x.IsActive == isActive.Value);
        }

        // 4. 排序返回
        return await query
            .OrderBy(x => x.SortOrder)
            .ThenByDescending(x => x.CreatedAt)
            .ToListAsync(cancellationToken);
    }

    /// <inheritdoc />
    public Task AddAsync(TenantPackage package, CancellationToken cancellationToken = default)
    {
        return context.TenantPackages.AddAsync(package, cancellationToken).AsTask();
    }

    /// <inheritdoc />
    public Task UpdateAsync(TenantPackage package, CancellationToken cancellationToken = default)
    {
        context.TenantPackages.Update(package);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public async Task DeleteAsync(long id, CancellationToken cancellationToken = default)
    {
        var entity = await context.TenantPackages.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
        if (entity != null)
        {
            context.TenantPackages.Remove(entity);
        }
    }

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