using RelayServer.Models;
using SurrealDb.Net;

namespace RelayServer.Services.Data;

public sealed class ClientKeyService
{
    private readonly SurrealDbClient _db;

    public ClientKeyService(SurrealDbClient db)
    {
        _db = db;
    }

    public async Task RegisterOrUpdateKeyAsync(string username, string publicKey)
    {
        var allKeys = await _db.Select<ClientPublicKeys>("client_public_keys");

        var existing = allKeys.FirstOrDefault(x => x.Username == username);

        if (existing is null)
        {
            await _db.Create("client_public_keys", new ClientPublicKeys
            {
                Username = username,
                PublicKey = publicKey,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            });

            Console.WriteLine($"Stored public key for {username}");
            return;
        }

        existing.PublicKey = publicKey;
        existing.UpdatedAt = DateTime.UtcNow;

        await _db.Merge<ClientPublicKeys, ClientPublicKeys>(new ClientPublicKeys
        {
            Id = existing.Id,
            Username = existing.Username,
            PublicKey = existing.PublicKey,
            CreatedAt = existing.CreatedAt,
            UpdatedAt = existing.UpdatedAt
        });

        Console.WriteLine($"Updated public key for {username}");
    }

    public async Task<ClientPublicKeys?> GetByUsernameAsync(string username)
    {
        var allKeys = await _db.Select<ClientPublicKeys>("client_public_keys");
        return allKeys.FirstOrDefault(x => x.Username == username);
    }
    
    public async Task<List<ClientPublicKeys>> GetAllAsync()
    {
        var allKeys = await _db.Select<ClientPublicKeys>("client_public_keys");
        return allKeys.ToList();
    }
}