using ColaFlow.Modules.Mcp.Domain.Entities;
using ColaFlow.Modules.Mcp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;

namespace ColaFlow.Modules.Mcp.Infrastructure.Persistence.Repositories;

/// <summary>
/// Repository implementation for MCP API Keys
/// </summary>
public class McpApiKeyRepository : IMcpApiKeyRepository
{
    private readonly McpDbContext _context;

    public McpApiKeyRepository(McpDbContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<McpApiKey?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.ApiKeys
            .FirstOrDefaultAsync(k => k.Id == id, cancellationToken);
    }

    public async Task<McpApiKey?> GetByPrefixAsync(string keyPrefix, CancellationToken cancellationToken = default)
    {
        return await _context.ApiKeys
            .FirstOrDefaultAsync(k => k.KeyPrefix == keyPrefix, cancellationToken);
    }

    public async Task<List<McpApiKey>> GetByTenantIdAsync(Guid tenantId, CancellationToken cancellationToken = default)
    {
        return await _context.ApiKeys
            .Where(k => k.TenantId == tenantId)
            .OrderByDescending(k => k.CreatedAt)
            .ToListAsync(cancellationToken);
    }

    public async Task<List<McpApiKey>> GetByUserIdAsync(Guid userId, Guid tenantId, CancellationToken cancellationToken = default)
    {
        return await _context.ApiKeys
            .Where(k => k.UserId == userId && k.TenantId == tenantId)
            .OrderByDescending(k => k.CreatedAt)
            .ToListAsync(cancellationToken);
    }

    public async Task AddAsync(McpApiKey apiKey, CancellationToken cancellationToken = default)
    {
        await _context.ApiKeys.AddAsync(apiKey, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);
    }

    public async Task UpdateAsync(McpApiKey apiKey, CancellationToken cancellationToken = default)
    {
        _context.ApiKeys.Update(apiKey);
        await _context.SaveChangesAsync(cancellationToken);
    }

    public async Task DeleteAsync(McpApiKey apiKey, CancellationToken cancellationToken = default)
    {
        _context.ApiKeys.Remove(apiKey);
        await _context.SaveChangesAsync(cancellationToken);
    }

    public async Task<bool> ExistsByPrefixAsync(string keyPrefix, CancellationToken cancellationToken = default)
    {
        return await _context.ApiKeys
            .AnyAsync(k => k.KeyPrefix == keyPrefix, cancellationToken);
    }
}
