using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Identity.Entities;
using TakeoutSaaS.Domain.Identity.Enums;
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 async Task<IReadOnlyList<MenuDefinition>> GetByPortalAsync(PortalType portal, CancellationToken cancellationToken = default)
    {
        // 1. 按门户类型查询菜单（忽略租户过滤器）
        var menus = await dbContext.MenuDefinitions
            .IgnoreQueryFilters()
            .AsNoTracking()
            .Where(x => x.Portal == portal && x.DeletedAt == null)
            .OrderBy(x => x.ParentId)
            .ThenBy(x => x.SortOrder)
            .ToListAsync(cancellationToken);

        return menus;
    }

    /// <inheritdoc />
    public async Task<MenuDefinition?> FindByIdAsync(long id, CancellationToken cancellationToken = default)
    {
        // 1. 按 ID 查询菜单（忽略租户过滤器）
        return await dbContext.MenuDefinitions
            .IgnoreQueryFilters()
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == id && x.DeletedAt == null, 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, CancellationToken cancellationToken = default)
    {
        // 1. 查询目标（忽略租户过滤器）
        var entity = await dbContext.MenuDefinitions
            .IgnoreQueryFilters()
            .FirstOrDefaultAsync(x => x.Id == id, cancellationToken);

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

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