using System;
using System.Collections.Generic;
using System.Linq;

namespace AutoIngest.Core
{
    /// <summary>
    /// In-memory view of the opt-in device registry persisted in <see cref="AppConfig"/>.
    /// Only devices whose <see cref="DeviceIdentity.Id"/> matches an entry here are imported
    /// automatically; everything else is prompted or skipped per <see cref="AppConfig.PromptOnUnknown"/>.
    /// </summary>
    public class DeviceRegistry
    {
        readonly AppConfig _config;

        public DeviceRegistry(AppConfig config)
        {
            _config = config;
        }

        /// <summary>True if a device with the given fingerprint has been registered.</summary>
        public bool IsRegistered(string deviceId) =>
            _config.Devices.Any(d => string.Equals(d.Id, deviceId, StringComparison.OrdinalIgnoreCase));

        public RegisteredDevice? Find(string deviceId) =>
            _config.Devices.FirstOrDefault(d =>
                string.Equals(d.Id, deviceId, StringComparison.OrdinalIgnoreCase));

        /// <summary>Registers a device. No-op if already present (updates name/kind if changed).</summary>
        public void Register(string id, string name, string kind)
        {
            var existing = Find(id);
            if (existing != null)
            {
                existing.Name = name;
                existing.Kind = kind;
                return;
            }
            _config.Devices.Add(new RegisteredDevice
            {
                Id = id,
                Name = name,
                Kind = kind,
                AddedUtc = DateTime.UtcNow
            });
        }

        public bool Remove(string deviceId)
        {
            var existing = Find(deviceId);
            return existing != null && _config.Devices.Remove(existing);
        }

        public IReadOnlyList<RegisteredDevice> All => _config.Devices;

        public void Save() => ConfigManager.SaveConfig(_config);
    }
}
