import { beforeEach, describe, expect, it, vi } from 'vitest';

vi.mock('../../../../shared/state', async () => {
  const navigate = vi.fn();
  const setState = vi.fn();
  const sendMessage = vi.fn();
  const getState = vi.fn(() => ({
    view: 'add', entries: [], selectedId: null, selectedItem: null, selectedIndex: 0,
    searchQuery: '', activeGroup: null, error: null, loading: false,
    capturedTabId: null, capturedUrl: '', newType: 'key',
  }));
  const escapeHtml = (s: string) => s
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  return { navigate, setState, sendMessage, getState, escapeHtml, popOutToTab: vi.fn(), isInTab: vi.fn(() => false), openVaultTab: vi.fn() };
});

import { renderForm } from '../key';
import { sendMessage } from '../../../../shared/state';

describe('Key save shape', () => {
  beforeEach(() => {
    document.body.innerHTML = '<div id="app"></div>';
    vi.mocked(sendMessage).mockReset();
    vi.mocked(sendMessage).mockResolvedValue({ ok: true, data: { id: 'fakeid0000000000', items: [] } });
  });

  it('requires key_material and emits all populated fields', async () => {
    const app = document.getElementById('app')!;
    renderForm(app, 'add', null);

    (document.getElementById('f-title') as HTMLInputElement).value = 'github ssh';
    (document.getElementById('f-key-material') as HTMLTextAreaElement).value = '-----BEGIN OPENSSH PRIVATE KEY-----\nfoo\n-----END...';
    (document.getElementById('f-label') as HTMLInputElement).value = 'work laptop';
    (document.getElementById('f-public-key') as HTMLTextAreaElement).value = 'ssh-ed25519 AAAA...';
    (document.getElementById('f-algorithm') as HTMLInputElement).value = 'ed25519';

    document.getElementById('save-btn')!.click();
    await new Promise(r => setTimeout(r, 5));

    const calls = vi.mocked(sendMessage).mock.calls;
    const addCall = calls.find(([msg]) => (msg as { type: string }).type === 'add_item');
    const msg = addCall![0] as { type: 'add_item'; item: any };
    expect(msg.item.type).toBe('key');
    expect(msg.item.core).toEqual({
      type: 'key',
      key_material: '-----BEGIN OPENSSH PRIVATE KEY-----\nfoo\n-----END...',
      label: 'work laptop',
      public_key: 'ssh-ed25519 AAAA...',
      algorithm: 'ed25519',
    });
  });

  it('rejects empty key_material', async () => {
    const app = document.getElementById('app')!;
    renderForm(app, 'add', null);
    (document.getElementById('f-title') as HTMLInputElement).value = 'no key';
    document.getElementById('save-btn')!.click();
    await new Promise(r => setTimeout(r, 5));

    const calls = vi.mocked(sendMessage).mock.calls;
    const addCall = calls.find(([msg]) => (msg as { type: string }).type === 'add_item');
    expect(addCall).toBeUndefined();
  });
});
