// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createTradeProfile } from './profileApi';

vi.mock('./authSession', () => ({
  getPlatformAccessToken: vi.fn(async () => 'test-token'),
}));

vi.mock('./runtime', () => ({
  tradingRuntime: { tradingApiUrl: 'https://trading.test' },
}));

describe('profileApi profile update notifications', () => {
  beforeEach(() => {
    vi.restoreAllMocks();
  });

  it('dispatches profiles-updated after creating a trade profile', async () => {
    const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
      ok: true,
      json: async () => ({
        profile: {
          id: 'profile-visual-1',
          name: 'Visual Strategy',
          symbols: 'AAPL',
          allocated_capital: 1000,
          risk_per_trade_percent: 1,
          is_active: false,
          strategy_config: { type: 'visual', rules: [] },
        },
      }),
    } as Response);
    const listener = vi.fn();
    window.addEventListener('profiles-updated', listener);

    await createTradeProfile({
      name: 'Visual Strategy',
      symbols: 'AAPL',
      allocated_capital: 1000,
      risk_per_trade_percent: 1,
      is_active: false,
      strategy_config: { type: 'visual', rules: [] },
    });

    expect(fetchMock).toHaveBeenCalledWith(
      'https://trading.test/api/profiles',
      expect.objectContaining({ method: 'POST' }),
    );
    expect(listener).toHaveBeenCalledTimes(1);
    window.removeEventListener('profiles-updated', listener);
  });
});
