using System;
using System.Linq;
using System.Threading.Tasks;
using Sozsoft.Platform;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;
using Volo.Abp.PermissionManagement;
namespace Sozsoft.Mcp.Data;
///
/// Kaldirilan McpServers.Develop yetkisini McpServers.Write'a tasir: Develop verilmis
/// rol/kullanicilara Write verilir, sonra Develop'un atamalari ve tanimi silinir. Seed yalnizca
/// ekledigi icin tanim bu adim olmadan yetki ekraninda sahipsiz kalir, o kullanicilar da
/// gelistirme araclarini kaybederdi. Develop kalmadiginda hicbir sey yapmaz; tekrar calismasi guvenlidir.
///
public class McpDevelopPermissionMergeDataSeedContributor(
IRepository grantRepository,
IRepository definitionRepository,
IGuidGenerator guidGenerator) : IDataSeedContributor, ITransientDependency
{
private const string LegacyDevelopPermission = PlatformConsts.AppCodes.DeveloperKits.McpServers.McpServer + ".Develop";
private const string WritePermission = PlatformConsts.AppCodes.DeveloperKits.McpServers.Write;
public async Task SeedAsync(DataSeedContext context)
{
// Develop yalnizca host tarafinda tanimliydi; kiraci turlarinda atamasi olamaz.
if (context.TenantId is not null)
{
return;
}
var developGrants = await grantRepository.GetListAsync(g => g.Name == LegacyDevelopPermission);
if (developGrants.Count > 0)
{
var writeGrants = await grantRepository.GetListAsync(g => g.Name == WritePermission);
var missing = developGrants
.Where(d => !writeGrants.Any(w => w.ProviderName == d.ProviderName && w.ProviderKey == d.ProviderKey))
.Select(d => new PermissionGrant(guidGenerator.Create(), WritePermission, d.ProviderName, d.ProviderKey, d.TenantId))
.ToList();
await grantRepository.InsertManyAsync(missing, autoSave: true);
await grantRepository.DeleteManyAsync(developGrants, autoSave: true);
}
await definitionRepository.DeleteAsync(p => p.Name == LegacyDevelopPermission, autoSave: true);
}
}