/**
 * GraphQL API Integration Tests
 */

import { describe, it, expect, beforeAll } from '@jest/globals';
import { GraphQLClient } from 'graphql-request';

const GRAPHQL_URL = process.env.GRAPHQL_URL || 'http://localhost:4000/graphql';
const runIntegration = process.env.RUN_EMONEY_GRAPHQL_INTEGRATION === '1';
const describeIfConfigured = runIntegration ? describe : describe.skip;

type TokenQueryResult = {
  token: {
    code: string;
    address: string;
    name: string;
    symbol: string;
    policy: {
      lienMode: string;
    };
  };
};

type TriggersQueryResult = {
  triggers: {
    items: Array<{
      triggerId: string;
      rail: string;
      state: string;
    }>;
    total: number;
  };
};

type DeployTokenMutationResult = {
  deployToken: {
    code: string;
    address: string;
  };
};

describeIfConfigured('GraphQL API Integration Tests', () => {
  let client: GraphQLClient;

  beforeAll(() => {
    client = new GraphQLClient(GRAPHQL_URL, {
      headers: {
        Authorization: `Bearer ${process.env.ACCESS_TOKEN || 'test-token'}`,
      },
    });
  });

  describe('Queries', () => {
    it('should query token', async () => {
      const query = `
        query GetToken($code: String!) {
          token(code: $code) {
            code
            address
            name
            symbol
            policy {
              lienMode
            }
          }
        }
      `;

      const data = await client.request<TokenQueryResult>(query, { code: 'USDW' });
      expect(data).toHaveProperty('token');
      expect(data.token).toHaveProperty('code');
    });

    it('should query triggers', async () => {
      const query = `
        query GetTriggers($filter: TriggerFilter, $paging: Paging) {
          triggers(filter: $filter, paging: $paging) {
            items {
              triggerId
              rail
              state
            }
            total
          }
        }
      `;

      const data = await client.request<TriggersQueryResult>(query, {
        filter: { state: 'PENDING' },
        paging: { limit: 10, offset: 0 },
      });

      expect(data).toHaveProperty('triggers');
      expect(data.triggers).toHaveProperty('items');
    });
  });

  describe('Mutations', () => {
    it('should deploy token via mutation', async () => {
      const mutation = `
        mutation DeployToken($input: DeployTokenInput!) {
          deployToken(input: $input) {
            code
            address
          }
        }
      `;

      const data = await client.request<DeployTokenMutationResult>(mutation, {
        input: {
          name: 'Test Token',
          symbol: 'TEST',
          decimals: 18,
          issuer: '0x1234567890123456789012345678901234567890',
        },
      });

      expect(data).toHaveProperty('deployToken');
      expect(data.deployToken).toHaveProperty('code');
    });
  });
});
