import { GraphQLResponse, Position } from '../types.js';

type FetchFn = typeof fetch;

export class GraphQLService {
  constructor(
    private readonly endpoint: string,
    private readonly fetchFn: FetchFn = fetch
  ) {
    if (!endpoint) {
      throw new Error('GraphQL endpoint is required');
    }
  }

  getEndpoint(): string {
    return this.endpoint;
  }

  async fetchActivePositions(query: string): Promise<Position[]> {
    const response = await this.fetchFn(this.endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query }),
    });

    if (!response.ok) {
      throw new Error(`GraphQL request failed with status ${response.status}`);
    }

    const payload = (await response.json()) as GraphQLResponse;
    if (payload.errors && payload.errors.length > 0) {
      const messages = payload.errors.map(error => error.message).join('; ');
      throw new Error(`GraphQL responded with errors: ${messages}`);
    }

    return payload.data?.positionss?.items ?? [];
  }
}
