using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Identity.Entities;
using TakeoutSaaS.Domain.Identity.Repositories;
using TakeoutSaaS.Infrastructure.Identity.Persistence;

namespace TakeoutSaaS.Infrastructure.Identity.Repositories;

/// <summary>
/// 菜单仓储 EF 实现。
/// </summary>
public sealed class EfMenuRepository(IdentityDbContext dbContext) : IMenuRepository
{
    /// <inheritdoc />
    public Task<IReadOnlyList<MenuDefinition>> GetByTenantAsync(long tenantId, CancellationToken cancellationToken = default)
    {
        return dbContext.MenuDefinitions
            .AsNoTracking()
            .Where(x => x.TenantId == tenantId)
            .OrderBy(x => x.ParentId)
            .ThenBy(x => x.SortOrder)
            .ToListAsync(cancellationToken)
            .ContinueWith(t => (IReadOnlyList<MenuDefinition>)t.Result, cancellationToken);
    }

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

    /// <inheritdoc />
    public Task AddAsync(MenuDefinition menu, CancellationToken cancellationToken = default)
    {
        return dbContext.MenuDefinitions.AddAsync(menu, cancellationToken).AsTask();
    }

    /// <inheritdoc />
    public Task UpdateAsync(MenuDefinition menu, CancellationToken cancellationToken = default)
    {
        dbContext.MenuDefinitions.Update(menu);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public async Task DeleteAsync(long id, long tenantId, CancellationToken cancellationToken = default)
    {
        // 1. 查询目标
        var entity = await dbContext.MenuDefinitions
            .FirstOrDefaultAsync(x => x.Id == id && x.TenantId == tenantId, cancellationToken);

        // 2. 存在则删除
        if (entity is not null)
        {
            dbContext.MenuDefinitions.Remove(entity);
        }
    }

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