using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.SystemParameters.Entities;
using TakeoutSaaS.Domain.SystemParameters.Repositories;
using TakeoutSaaS.Infrastructure.Dictionary.Persistence;

namespace TakeoutSaaS.Infrastructure.Dictionary.Repositories;

/// <summary>
/// 系统参数 EF Core 仓储实现。
/// </summary>
public sealed class EfSystemParameterRepository(DictionaryDbContext context) : ISystemParameterRepository
{
    /// <inheritdoc />
    public Task<SystemParameter?> FindByIdAsync(long id, CancellationToken cancellationToken = default)
    {
        return context.SystemParameters
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
    }

    /// <inheritdoc />
    public Task<SystemParameter?> FindByKeyAsync(string key, CancellationToken cancellationToken = default)
    {
        var normalizedKey = key.Trim();
        return context.SystemParameters
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Key == normalizedKey, cancellationToken);
    }

    /// <inheritdoc />
    public async Task<IReadOnlyList<SystemParameter>> SearchAsync(string? keyword, bool? isEnabled, CancellationToken cancellationToken = default)
    {
        var query = context.SystemParameters.AsNoTracking();

        if (!string.IsNullOrWhiteSpace(keyword))
        {
            var normalized = keyword.Trim();
            query = query.Where(x => x.Key.Contains(normalized) || (x.Description != null && x.Description.Contains(normalized)));
        }

        if (isEnabled.HasValue)
        {
            query = query.Where(x => x.IsEnabled == isEnabled.Value);
        }

        var parameters = await query
            .OrderBy(x => x.SortOrder)
            .ThenBy(x => x.Key)
            .ToListAsync(cancellationToken);

        return parameters;
    }

    /// <inheritdoc />
    public Task AddAsync(SystemParameter parameter, CancellationToken cancellationToken = default)
    {
        return context.SystemParameters.AddAsync(parameter, cancellationToken).AsTask();
    }

    /// <inheritdoc />
    public Task RemoveAsync(SystemParameter parameter, CancellationToken cancellationToken = default)
    {
        context.SystemParameters.Remove(parameter);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task UpdateAsync(SystemParameter parameter, CancellationToken cancellationToken = default)
    {
        context.SystemParameters.Update(parameter);
        return Task.CompletedTask;
    }

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