// PRE-GENERATED (design session). Behavior for one API-key row (+ 발급 링크).
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using DansoriEQ.Core.Security;

namespace DansoriEQ.App.Controls;

public partial class ApiKeyRow : UserControl
{
    private ISecretStore? _store;
    private string _providerKey = "";
    private string? _helpUrl;

    public ApiKeyRow() => InitializeComponent();

    /// <summary>Wire the row to a provider + store. helpUrl shows a "키 발급 방법" link.</summary>
    public void Initialize(ISecretStore store, string providerKey, string displayName, string? helpUrl = null)
    {
        _store = store;
        _providerKey = providerKey;
        _helpUrl = helpUrl;
        LblName.Text = displayName;
        BtnHelpLink.Visibility = string.IsNullOrEmpty(helpUrl) ? Visibility.Collapsed : Visibility.Visible;
        Refresh();
    }

    private void Refresh()
    {
        bool has = _store?.Has(_providerKey) ?? false;
        InputPanel.Visibility = has ? Visibility.Collapsed : Visibility.Visible;
        SavedPanel.Visibility = has ? Visibility.Visible : Visibility.Collapsed;
    }

    private void Save_Click(object sender, RoutedEventArgs e)
    {
        var value = Pwd.Password?.Trim();
        if (string.IsNullOrEmpty(value) || _store is null) return;
        _store.Save(_providerKey, value);   // encrypted at rest
        Pwd.Clear();
        Refresh();
    }

    private void Delete_Click(object sender, RoutedEventArgs e)
    {
        _store?.Delete(_providerKey);
        Refresh();
    }

    private void HelpLink_Click(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(_helpUrl)) return;
        try { Process.Start(new ProcessStartInfo(_helpUrl) { UseShellExecute = true }); }
        catch { /* ignore */ }
    }
}
