using Predictalytics.Domain.Entities;
using Predictalytics.Domain.Interfaces;
using Microsoft.Extensions.Logging;

namespace Predictalytics.Application.Services;

public class WatchlistService
{
    private readonly IWatchlistRepository _repo;
    private readonly ITraderRepository _traderRepo;
    private readonly ILogger<WatchlistService> _logger;

    public WatchlistService(IWatchlistRepository repo, ITraderRepository traderRepo, ILogger<WatchlistService> logger)
    { _repo = repo; _traderRepo = traderRepo; _logger = logger; }

    public Task<IReadOnlyList<WatchlistEntry>> GetAllAsync(CancellationToken ct = default) => _repo.GetAllAsync(ct);

    public async Task AddAsync(int traderId, string label, string? notes = null, CancellationToken ct = default)
    {
        var existing = await _repo.GetByTraderIdAsync(traderId, ct);
        if (existing != null) return;
        await _repo.AddAsync(new WatchlistEntry { TraderId = traderId, Label = label, Notes = notes }, ct);
        var trader = await _traderRepo.GetByIdAsync(traderId, ct);
        _logger.LogInformation("Added {Trader} to watchlist", trader?.DisplayName ?? traderId.ToString());
    }

    public async Task RemoveAsync(int id, CancellationToken ct = default)
    {
        await _repo.RemoveAsync(id, ct);
        _logger.LogInformation("Removed watchlist entry {Id}", id);
    }

    public async Task RemoveByTraderIdAsync(int traderId, CancellationToken ct = default)
    {
        var existing = await _repo.GetByTraderIdAsync(traderId, ct);
        if (existing != null)
        {
            await _repo.RemoveAsync(existing.Id, ct);
            _logger.LogInformation("Removed trader {TraderId} from watchlist", traderId);
        }
    }
}
