import { setEvents } from '../logic/sources/setEvents';

import { ValidAccessKey } from '@buildable/types';
import { createSource } from '../logic/sources/createSource';
import {
	createDestination,
	deleteDestination,
	deleteSource,
	listDestinations,
	listSources,
} from '../logic';
import { makeId } from '@buildable/utils';
import { createClient } from '../client';

require('dotenv').config();
jest.setTimeout(30000);

describe('Connections APIs Specs', () => {
	it('Should create a Stripe source, subscribe to customer.created event, create a mongodb destination', async () => {
		const client = createClient(
			process.env.BUILDABLE_SECRET_KEY as ValidAccessKey
		);

		const source = await createSource(client, {
			type: 'stripe',
			group: `my-stripe-source-${makeId(4)}`,
			label: `my-stripe-source-${makeId(4)}`,
			config: {
				STRIPE_SECRET_KEY: process.env.CONNECTIONS_TEST_STRIPE_SECRET_KEY,
			},
		});

		expect(source).toHaveProperty('key');

		await new Promise((resolve) => setTimeout(resolve, 5000));

		const subscribe = await setEvents(client, {
			type: 'stripe',
			key: source.key,
			events: ['customer.created'],
		});

		expect(subscribe).toHaveProperty('success', true);

		const destination = await createDestination(client, {
			type: 'mongodb',
			group: `my-mongodb-destination-${makeId(4)}`,
			label: `my-mongodb-destination-${makeId(4)}`,
			config: {
				MONGODB_URI: process.env.CONNECTIONS_TEST_MONGODB_URI,
			},
		});

		expect(destination).toHaveProperty('key');

		await new Promise((resolve) => setTimeout(resolve, 5000));

		const deleteSourceResult = await deleteSource(client, {
			key: source.key,
		});

		expect(deleteSourceResult).toHaveProperty('success', true);

		const deleteDestinationResult = await deleteDestination(client, {
			key: destination.key,
		});

		expect(deleteDestinationResult).toHaveProperty('success', true);
	});

	it('Should list all sources', async () => {
		const client = createClient(
			process.env.BUILDABLE_SECRET_KEY as ValidAccessKey
		);

		const sourceList = await listSources(client);

		expect(sourceList).toHaveProperty('rows');
	});

	it('Should list all destinations', async () => {
		const client = createClient(
			process.env.BUILDABLE_SECRET_KEY as ValidAccessKey
		);

		const destinationList = await listDestinations(client);

		expect(destinationList).toHaveProperty('rows');
	});
});

