import { firstValueFrom, take } from 'rxjs';

import { AppPluginConfig } from '@grafana/data';

import { log } from '../logs/log';
import { resetLogMock } from '../logs/testUtils';
import { basicApp } from '../test-fixtures/config.apps';
import { isGrafanaDevMode } from '../utils';

import { AddedFunctionsRegistry } from './AddedFunctionsRegistry';
import { MSG_CANNOT_REGISTER_READ_ONLY } from './Registry';

jest.mock('../utils', () => ({
  ...jest.requireActual('../utils'),

  // Manually set the dev mode to false
  // (to make sure that by default we are testing a production scneario)
  isGrafanaDevMode: jest.fn().mockReturnValue(false),
}));

jest.mock('../logs/log', () => {
  const { createLogMock } = jest.requireActual('../logs/testUtils');
  const original = jest.requireActual('../logs/log');

  return {
    ...original,
    log: createLogMock(),
  };
});

describe('addedFunctionsRegistry', () => {
  const pluginId = basicApp.id;
  const apps = [basicApp];
  const createRegistry = async (override: AppPluginConfig[] = apps) => new AddedFunctionsRegistry(override);

  beforeEach(() => {
    resetLogMock(log);
    jest.mocked(isGrafanaDevMode).mockReturnValue(false);
  });

  it('should return empty registry when no extensions registered', async () => {
    const addedFunctionsRegistry = await createRegistry();
    const observable = addedFunctionsRegistry.asObservable();
    const registry = await firstValueFrom(observable);
    expect(registry).toEqual({});
  });

  it('should be possible to register function extensions in the registry', async () => {
    const addedFunctionsRegistry = await createRegistry();

    addedFunctionsRegistry.register({
      pluginId,
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn(),
        },
        {
          title: 'Function 2',
          description: 'Function 2 description',
          targets: 'plugins/myorg-basic-app/start',
          fn: jest.fn(),
        },
      ],
    });

    const registry = await addedFunctionsRegistry.getState();

    expect(registry).toEqual({
      'grafana/dashboard/panel/menu': [
        {
          pluginId: pluginId,
          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
      ],
      'plugins/myorg-basic-app/start': [
        {
          pluginId: pluginId,
          title: 'Function 2',
          description: 'Function 2 description',
          extensionPointId: 'plugins/myorg-basic-app/start',
          fn: expect.any(Function),
        },
      ],
    });
  });

  it('should not emit when registering with empty configs', async () => {
    const addedFunctionsRegistry = await createRegistry();
    const observable = addedFunctionsRegistry.asObservable();
    const subscribeCallback = jest.fn();

    observable.subscribe(subscribeCallback);

    // Initial subscription should be called once with empty registry
    expect(subscribeCallback).toHaveBeenCalledTimes(1);

    // Register with empty configs - should not emit
    addedFunctionsRegistry.register({
      pluginId,
      configs: [],
    });

    // Should still only be called once (no new emission)
    expect(subscribeCallback).toHaveBeenCalledTimes(1);
    expect(subscribeCallback.mock.calls[0][0]).toEqual({});

    // Verify registry state is still empty
    const registry = await addedFunctionsRegistry.getState();
    expect(registry).toEqual({});
  });

  it('should not change registry state when registering with empty configs after previous registrations', async () => {
    const addedFunctionsRegistry = await createRegistry();

    // First register some extensions
    addedFunctionsRegistry.register({
      pluginId,
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn(),
        },
      ],
    });

    const registryBefore = await addedFunctionsRegistry.getState();
    expect(Object.keys(registryBefore)).toHaveLength(1);

    // Register with empty configs - should not change state
    addedFunctionsRegistry.register({
      pluginId,
      configs: [],
    });

    const registryAfter = await addedFunctionsRegistry.getState();
    expect(registryAfter).toEqual(registryBefore);
  });

  it('should be possible to asynchronously register function extensions for the same placement (different plugins)', async () => {
    const pluginId1 = 'grafana-basic-app';
    const pluginId2 = 'grafana-basic-app2';
    const reactiveRegistry = await createRegistry();

    // Register extensions for the first plugin
    reactiveRegistry.register({
      pluginId: pluginId1,
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    const registry1 = await reactiveRegistry.getState();

    expect(registry1).toEqual({
      'grafana/dashboard/panel/menu': [
        {
          pluginId: pluginId1,
          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
      ],
    });

    // Register extensions for the second plugin to a different placement
    reactiveRegistry.register({
      pluginId: pluginId2,
      configs: [
        {
          title: 'Function 2',
          description: 'Function 2 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    const registry2 = await reactiveRegistry.getState();

    expect(registry2).toEqual({
      'grafana/dashboard/panel/menu': [
        {
          pluginId: pluginId1,
          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
        {
          pluginId: pluginId2,
          title: 'Function 2',
          description: 'Function 2 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
      ],
    });
  });

  it('should be possible to asynchronously register function extensions for a different placement (different plugin)', async () => {
    const pluginId1 = 'grafana-basic-app';
    const pluginId2 = 'grafana-basic-app2';
    const reactiveRegistry = await createRegistry();

    // Register extensions for the first plugin
    reactiveRegistry.register({
      pluginId: pluginId1,
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    const registry1 = await reactiveRegistry.getState();

    expect(registry1).toEqual({
      'grafana/dashboard/panel/menu': [
        {
          pluginId: pluginId1,

          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
      ],
    });

    // Register extensions for the second plugin to a different placement
    reactiveRegistry.register({
      pluginId: pluginId2,
      configs: [
        {
          title: 'Function 2',
          description: 'Function 2 description',
          targets: 'plugins/myorg-basic-app/start',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    const registry2 = await reactiveRegistry.getState();

    expect(registry2).toEqual({
      'grafana/dashboard/panel/menu': [
        {
          pluginId: pluginId1,
          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
      ],
      'plugins/myorg-basic-app/start': [
        {
          pluginId: pluginId2,
          title: 'Function 2',
          description: 'Function 2 description',
          extensionPointId: 'plugins/myorg-basic-app/start',
          fn: expect.any(Function),
        },
      ],
    });
  });

  it('should be possible to asynchronously register function extensions for the same placement (same plugin)', async () => {
    const pluginId = 'grafana-basic-app';
    const reactiveRegistry = await createRegistry();

    // Register extensions for the first extension point
    reactiveRegistry.register({
      pluginId: pluginId,
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    // Register extensions to a different extension point
    reactiveRegistry.register({
      pluginId: pluginId,
      configs: [
        {
          title: 'Function 2',
          description: 'Function 2 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    const registry2 = await reactiveRegistry.getState();

    expect(registry2).toEqual({
      'grafana/dashboard/panel/menu': [
        {
          pluginId: pluginId,

          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
        {
          pluginId: pluginId,

          title: 'Function 2',
          description: 'Function 2 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
      ],
    });
  });

  it('should be possible to asynchronously register function extensions for a different placement (same plugin)', async () => {
    const pluginId = 'grafana-basic-app';
    const reactiveRegistry = await createRegistry();

    // Register extensions for the first extension point
    reactiveRegistry.register({
      pluginId: pluginId,
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    // Register extensions to a different extension point
    reactiveRegistry.register({
      pluginId: pluginId,
      configs: [
        {
          title: 'Function 2',
          description: 'Function 2 description',
          targets: 'plugins/myorg-basic-app/start',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    const registry2 = await reactiveRegistry.getState();

    expect(registry2).toEqual({
      'grafana/dashboard/panel/menu': [
        {
          pluginId: pluginId,

          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
      ],
      'plugins/myorg-basic-app/start': [
        {
          pluginId: pluginId,

          title: 'Function 2',
          description: 'Function 2 description',
          extensionPointId: 'plugins/myorg-basic-app/start',
          fn: expect.any(Function),
        },
      ],
    });
  });

  it('should notify subscribers when the registry changes', async () => {
    const pluginId = 'grafana-basic-app';
    const reactiveRegistry = await createRegistry();
    const observable = reactiveRegistry.asObservable();
    const subscribeCallback = jest.fn();

    observable.subscribe(subscribeCallback);

    // Register extensions for the first plugin
    reactiveRegistry.register({
      pluginId: pluginId,
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    expect(subscribeCallback).toHaveBeenCalledTimes(2);

    // Register extensions for the first plugin
    reactiveRegistry.register({
      pluginId: 'another-plugin',
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    expect(subscribeCallback).toHaveBeenCalledTimes(3);

    const registry = subscribeCallback.mock.calls[2][0];

    expect(registry).toEqual({
      'grafana/dashboard/panel/menu': [
        {
          pluginId: pluginId,
          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
        {
          pluginId: 'another-plugin',
          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
      ],
    });
  });

  it('should give the last version of the registry for new subscribers', async () => {
    const pluginId = 'grafana-basic-app';
    const reactiveRegistry = await createRegistry();
    const observable = reactiveRegistry.asObservable();
    const subscribeCallback = jest.fn();

    reactiveRegistry.register({
      pluginId: pluginId,
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    observable.subscribe(subscribeCallback);
    expect(subscribeCallback).toHaveBeenCalledTimes(1);

    const registry = subscribeCallback.mock.calls[0][0];

    expect(registry).toEqual({
      'grafana/dashboard/panel/menu': [
        {
          pluginId: pluginId,
          title: 'Function 1',
          description: 'Function 1 description',
          extensionPointId: 'grafana/dashboard/panel/menu',
          fn: expect.any(Function),
        },
      ],
    });
  });

  it('should not register a function extension if it has an invalid fn function', async () => {
    const pluginId = 'grafana-basic-app';
    const reactiveRegistry = await createRegistry();
    const observable = reactiveRegistry.asObservable();
    const subscribeCallback = jest.fn();

    reactiveRegistry.register({
      pluginId: pluginId,
      configs: [
        {
          title: 'Function 1',
          description: 'Function 1 description',
          targets: 'grafana/dashboard/panel/menu',
          //@ts-ignore
          fn: '...',
        },
      ],
    });

    expect(log.error).toHaveBeenCalled();

    observable.subscribe(subscribeCallback);
    expect(subscribeCallback).toHaveBeenCalledTimes(1);

    const registry = subscribeCallback.mock.calls[0][0];
    expect(registry).toEqual({});
  });

  it('should not register a function extension if it has invalid properties (empty title)', async () => {
    const pluginId = 'grafana-basic-app';
    const reactiveRegistry = await createRegistry();
    const observable = reactiveRegistry.asObservable();
    const subscribeCallback = jest.fn();

    reactiveRegistry.register({
      pluginId: pluginId,
      configs: [
        {
          title: '',
          targets: 'grafana/dashboard/panel/menu',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    expect(log.error).toHaveBeenCalled();

    observable.subscribe(subscribeCallback);
    expect(subscribeCallback).toHaveBeenCalledTimes(1);

    const registry = subscribeCallback.mock.calls[0][0];
    expect(registry).toEqual({});
  });

  it('should not be possible to register a function on a read-only registry', async () => {
    const pluginId = 'grafana-basic-app';
    const registry = await createRegistry();
    const readOnlyRegistry = registry.readOnly();

    expect(() => {
      readOnlyRegistry.register({
        pluginId,
        configs: [
          {
            title: 'Function 2',
            description: 'Function 2 description',
            targets: 'plugins/myorg-basic-app/start',
            fn: jest.fn().mockReturnValue({}),
          },
        ],
      });
    }).toThrow(MSG_CANNOT_REGISTER_READ_ONLY);

    const currentState = await readOnlyRegistry.getState();
    expect(Object.keys(currentState)).toHaveLength(0);
  });

  it('should pass down fresh registrations to the read-only version of the registry', async () => {
    const pluginId = 'grafana-basic-app';
    const registry = await createRegistry();
    const readOnlyRegistry = registry.readOnly();
    const subscribeCallback = jest.fn();
    let readOnlyState;

    // Should have no extensions registered in the beginning
    readOnlyState = await readOnlyRegistry.getState();
    expect(Object.keys(readOnlyState)).toHaveLength(0);

    readOnlyRegistry.asObservable().subscribe(subscribeCallback);

    // Register an extension to the original (writable) registry
    registry.register({
      pluginId,
      configs: [
        {
          title: 'Function 2',
          description: 'Function 2 description',
          targets: 'plugins/myorg-basic-app/start',
          fn: jest.fn().mockReturnValue({}),
        },
      ],
    });

    // The read-only registry should have received the new extension
    readOnlyState = await readOnlyRegistry.getState();
    expect(Object.keys(readOnlyState)).toHaveLength(1);

    expect(subscribeCallback).toHaveBeenCalledTimes(2);
    expect(Object.keys(subscribeCallback.mock.calls[1][0])).toEqual(['plugins/myorg-basic-app/start']);
  });

  it('should not register a function added by a plugin in dev-mode if the meta-info is missing from the plugin.json', async () => {
    // Enabling dev mode
    jest.mocked(isGrafanaDevMode).mockReturnValue(true);

    const registry = await createRegistry();
    const fnConfig = {
      title: 'Function 1',
      description: 'Function 1 description',
      targets: 'grafana/dashboard/panel/menu',
      fn: jest.fn().mockReturnValue({}),
    };

    registry.register({
      pluginId,
      configs: [fnConfig],
    });

    const currentState = await registry.getState();

    expect(Object.keys(currentState)).toHaveLength(0);
    expect(log.error).toHaveBeenCalled();
  });

  it('should register a function added by core Grafana in dev-mode even if the meta-info is missing', async () => {
    // Enabling dev mode
    jest.mocked(isGrafanaDevMode).mockReturnValue(true);

    const registry = await createRegistry();
    const fnConfig = {
      title: 'Function 1',
      description: 'Function 1 description',
      targets: 'grafana/dashboard/panel/menu',
      fn: jest.fn().mockReturnValue({}),
    };

    registry.register({
      pluginId: 'grafana',
      configs: [fnConfig],
    });

    const currentState = await registry.getState();

    expect(Object.keys(currentState)).toHaveLength(1);
    expect(log.error).not.toHaveBeenCalled();
  });

  it('should register a function added by a plugin in production mode even if the meta-info is missing', async () => {
    // Production mode
    jest.mocked(isGrafanaDevMode).mockReturnValue(false);

    const registry = await createRegistry();
    const fnConfig = {
      title: 'Function 1',
      description: 'Function 1 description',
      targets: 'grafana/dashboard/panel/menu',
      fn: jest.fn().mockReturnValue({}),
    };

    registry.register({
      pluginId,
      configs: [fnConfig],
    });

    const currentState = await registry.getState();

    expect(Object.keys(currentState)).toHaveLength(1);
    expect(log.error).not.toHaveBeenCalled();
  });

  it('should register a function added by a plugin in dev-mode if the meta-info is present', async () => {
    // Enabling dev mode
    jest.mocked(isGrafanaDevMode).mockReturnValue(true);

    const fnConfig = {
      title: 'Function 1',
      description: 'Function 1 description',
      targets: ['grafana/dashboard/panel/menu'],
      fn: jest.fn().mockReturnValue({}),
    };
    const { description, targets, title } = fnConfig;
    const app = {
      ...basicApp,
      extensions: { ...basicApp.extensions, addedFunctions: [{ description, targets, title }] },
    };
    const registry = await createRegistry([app]);

    registry.register({
      pluginId,
      configs: [fnConfig],
    });

    const currentState = await registry.getState();

    expect(Object.keys(currentState)).toHaveLength(1);
    expect(log.error).not.toHaveBeenCalled();
  });

  describe('asObservableSlice', () => {
    it('should return the selected slice from the registry', async () => {
      const registry = await createRegistry();
      const extensionPointId = 'grafana/dashboard/panel/menu';

      registry.register({
        pluginId: 'test-plugin',
        configs: [
          {
            title: 'Test Function',
            description: 'Test description',
            targets: extensionPointId,
            fn: jest.fn(),
          },
        ],
      });

      const observable = registry.asObservableSlice((state) => state[extensionPointId]).pipe(take(1));

      await expect(observable).toEmitValuesWith((received) => {
        const [slice] = received;

        expect(slice).toBeDefined();
        expect(Array.isArray(slice)).toBe(true);
        expect(slice?.length).toBe(1);
        expect(slice?.[0].title).toBe('Test Function');
      });
    });

    it('should return undefined when the selected key does not exist', async () => {
      const registry = await createRegistry();
      const observable = registry.asObservableSlice((state) => state['non-existent-key']).pipe(take(1));

      await expect(observable).toEmitValuesWith((received) => {
        const [slice] = received;
        expect(slice).toBeUndefined();
      });
    });

    it('should only emit when the selected slice changes (distinctUntilChanged)', async () => {
      const registry = await createRegistry();
      const extensionPointId = 'grafana/dashboard/panel/menu';
      const subscribeCallback = jest.fn();

      const observable = registry.asObservableSlice((state) => state[extensionPointId]);
      observable.subscribe(subscribeCallback);

      // Initial empty state
      expect(subscribeCallback).toHaveBeenCalledTimes(1);
      expect(subscribeCallback.mock.calls[0][0]).toBeUndefined();

      // Register first function
      registry.register({
        pluginId: 'test-plugin-1',
        configs: [
          {
            title: 'Function 1',
            description: 'Description 1',
            targets: extensionPointId,
            fn: jest.fn(),
          },
        ],
      });

      // Should emit because the slice changed
      expect(subscribeCallback).toHaveBeenCalledTimes(2);
      expect(subscribeCallback.mock.calls[1][0]?.length).toBe(1);

      // Register another function to the same extension point
      registry.register({
        pluginId: 'test-plugin-2',
        configs: [
          {
            title: 'Function 2',
            description: 'Description 2',
            targets: extensionPointId,
            fn: jest.fn(),
          },
        ],
      });

      // Should emit because the slice changed (array reference changed)
      expect(subscribeCallback).toHaveBeenCalledTimes(3);
      expect(subscribeCallback.mock.calls[2][0]?.length).toBe(2);

      // Register a function to a different extension point
      registry.register({
        pluginId: 'test-plugin-3',
        configs: [
          {
            title: 'Function 3',
            description: 'Description 3',
            targets: 'grafana/other/point',
            fn: jest.fn(),
          },
        ],
      });

      // Should NOT emit because the selected slice (for extensionPointId) didn't change
      expect(subscribeCallback).toHaveBeenCalledTimes(3);
    });

    it('should deep freeze the selected slice', async () => {
      const registry = await createRegistry();
      const extensionPointId = 'grafana/dashboard/panel/menu';

      registry.register({
        pluginId: 'test-plugin',
        configs: [
          {
            title: 'Test Function',
            description: 'Test description',
            targets: extensionPointId,
            fn: jest.fn(),
          },
        ],
      });

      const observable = registry.asObservableSlice((state) => state[extensionPointId]).pipe(take(1));

      await expect(observable).toEmitValuesWith((received) => {
        const [slice] = received;

        expect(slice).toBeDefined();
        // @ts-expect-error - Testing that frozen objects cannot be modified
        expect(() => slice.push({})).toThrow();
        expect(() => (slice[0].title = 'Modified')).toThrow();
      });
    });

    it('should work with read-only registries', async () => {
      const registry = await createRegistry();
      const readOnlyRegistry = registry.readOnly();
      const extensionPointId = 'grafana/dashboard/panel/menu';

      registry.register({
        pluginId: 'test-plugin',
        configs: [
          {
            title: 'Test Function',
            description: 'Test description',
            targets: extensionPointId,
            fn: jest.fn(),
          },
        ],
      });

      const observable = readOnlyRegistry.asObservableSlice((state) => state[extensionPointId]).pipe(take(1));

      await expect(observable).toEmitValuesWith((received) => {
        const [slice] = received;

        expect(slice).toBeDefined();
        expect(Array.isArray(slice)).toBe(true);
        expect(slice?.length).toBe(1);
        expect(slice?.[0].title).toBe('Test Function');
      });
    });

    it('should emit immediately to new subscribers with the current slice value', async () => {
      const registry = await createRegistry();
      const extensionPointId = 'grafana/dashboard/panel/menu';

      registry.register({
        pluginId: 'test-plugin',
        configs: [
          {
            title: 'Test Function',
            description: 'Test description',
            targets: extensionPointId,
            fn: jest.fn(),
          },
        ],
      });

      // Subscribe after registration
      const observable = registry.asObservableSlice((state) => state[extensionPointId]);
      const subscribeCallback = jest.fn();
      observable.subscribe(subscribeCallback);

      // Should have been called immediately with the current value
      expect(subscribeCallback).toHaveBeenCalledTimes(1);
      expect(subscribeCallback.mock.calls[0][0]?.length).toBe(1);
      expect(subscribeCallback.mock.calls[0][0]?.[0].title).toBe('Test Function');
    });
  });
});
