import { describe, it, expect, vi, beforeEach } from 'vitest';
import { finishSetup } from '../setup';

describe('finishSetup', () => {
  beforeEach(() => {
    (global as any).chrome = {
      tabs: {
        create: vi.fn(() => Promise.resolve({ id: 999 })),
        getCurrent: vi.fn(() => Promise.resolve({ id: 42 })),
        remove: vi.fn(() => Promise.resolve()),
      },
      runtime: {
        getURL: vi.fn((p: string) => `chrome-extension://abc/${p}`),
      },
    };
  });

  it('opens vault.html in a new tab', async () => {
    await finishSetup();
    expect(chrome.runtime.getURL).toHaveBeenCalledWith('vault.html');
    expect(chrome.tabs.create).toHaveBeenCalledWith({
      url: 'chrome-extension://abc/vault.html',
    });
  });

  it('closes the current setup tab after opening the vault tab', async () => {
    await finishSetup();
    expect(chrome.tabs.getCurrent).toHaveBeenCalled();
    expect(chrome.tabs.remove).toHaveBeenCalledWith(42);
  });

  it('still opens the vault tab even if closing the setup tab fails', async () => {
    (chrome.tabs.remove as any).mockRejectedValueOnce(new Error('no permission'));
    await expect(finishSetup()).resolves.not.toThrow();
    expect(chrome.tabs.create).toHaveBeenCalled();
  });
});
