import { App as AntApp, ConfigProvider } from 'antd';
import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

import { AppContext, type AppContextValue } from '../../src/frontend/app-context';
import { I18nProvider } from '../../src/frontend/i18n/react';
import { api } from '../../src/frontend/services/api';
import { mailhubTheme } from '../../src/frontend/theme';
import type { ApiToken, RuntimeConfig } from '../../src/frontend/types';
import ApiTokens from '../../src/pages/ApiTokens';

describe('API token one-time secret', () => {
  it('removes the full token after the explicit acknowledgement', async () => {
    const user = userEvent.setup();
    const summary: ApiToken = {
      id: 9,
      name: 'CI sender',
      tokenPrefix: 'mh_12345678',
      scopes: ['send'],
      status: 'active',
      createdAt: '2026-07-14T00:00:00.000Z'
    };
    const fullToken = 'mh_12345678.full-secret-value';

    vi.spyOn(api, 'apiTokens')
      .mockResolvedValueOnce({ tokens: [] })
      .mockResolvedValue({ tokens: [summary] });
    const createToken = vi.spyOn(api, 'createApiToken').mockResolvedValue({
      token: { ...summary, token: fullToken }
    });

    renderPage();
    await screen.findByText('创建 Token 后可复制完整密钥；历史 Token 只显示前缀，示例中使用占位符。');
    await user.click(screen.getAllByRole('button', { name: /创建 Token/ })[0]);

    const editor = await screen.findByRole('dialog');
    await user.type(within(editor).getByLabelText('名称'), 'CI sender');
    await user.click(within(editor).getByRole('button', { name: /创建 Token/ }));

    await waitFor(() => expect(createToken).toHaveBeenCalledWith({
      name: 'CI sender',
      scopes: ['send'],
      expiresAt: null
    }));
    expect(await screen.findByText(fullToken)).not.toBeNull();

    const reveal = screen.getByRole('dialog', { name: 'API Token 已创建' });
    await user.click(within(reveal).getByRole('button', { name: /确.*认/ }));

    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'API Token 已创建' })).toBeNull());
    expect(await screen.findByText('mh_12345678...')).not.toBeNull();
    expect(screen.queryByRole('dialog', { name: 'API Token 已创建' })).toBeNull();
  });
});

function renderPage() {
  const context: AppContextValue = {
    user: { id: 1, username: 'operator', email: 'operator@example.test', role: 'admin', status: 'active' },
    config,
    refreshBootstrap: vi.fn(async () => undefined),
    logout: vi.fn(async () => undefined)
  };
  return render(
    <ConfigProvider theme={{ ...mailhubTheme, token: { ...mailhubTheme.token, motion: false } }}>
      <AntApp>
        <I18nProvider>
          <AppContext.Provider value={context}>
            <ApiTokens />
          </AppContext.Provider>
        </I18nProvider>
      </AntApp>
    </ConfigProvider>
  );
}

const config: RuntimeConfig = {
  appBaseUrl: 'https://mail.example.test',
  mailHostname: 'mail.example.test',
  sendingIp: '192.0.2.10',
  defaultSpfMechanisms: '',
  dmarcPolicy: 'none',
  dmarcRua: '',
  sendRequiresVerified: true,
  engagementTrackingEnabled: true,
  listUnsubscribeMailto: '',
  listUnsubscribeUrl: '',
  listUnsubscribePostEnabled: false,
  feedbackIdEnabled: false,
  reportAbuseTo: '',
  csaComplaintsTo: '',
  bounceAddress: '',
  bounceEnvelopeEnabled: false
};
