/**
 * API testing helpers
 */

import { FastifyInstance } from 'fastify';

export interface ApiResponse<T = unknown> {
  status: number;
  body: T;
  headers: Record<string, string>;
}

/**
 * Create API helpers for testing
 */
export function createApiHelpers(app: FastifyInstance) {
  return {
    async get<T = unknown>(path: string, headers?: Record<string, string>): Promise<ApiResponse<T>> {
      const response = await app.inject({
        method: 'GET',
        url: path,
        headers,
      });

      return {
        status: response.statusCode,
        body: (response.json() || response.body) as T,
        headers: response.headers as Record<string, string>,
      };
    },

    async post<T = unknown>(
      path: string,
      body?: unknown,
      headers?: Record<string, string>
    ): Promise<ApiResponse<T>> {
      const response = await app.inject({
        method: 'POST',
        url: path,
        payload: body as string | Buffer | object | undefined,
        headers: {
          'Content-Type': 'application/json',
          ...headers,
        },
      });

      return {
        status: response.statusCode,
        body: (response.json() || response.body) as T,
        headers: response.headers as Record<string, string>,
      };
    },

    async put<T = unknown>(
      path: string,
      body?: unknown,
      headers?: Record<string, string>
    ): Promise<ApiResponse<T>> {
      const response = await app.inject({
        method: 'PUT',
        url: path,
        payload: body as string | Buffer | object | undefined,
        headers: {
          'Content-Type': 'application/json',
          ...headers,
        },
      });

      return {
        status: response.statusCode,
        body: (response.json() || response.body) as T,
        headers: response.headers as Record<string, string>,
      };
    },

    async delete<T = unknown>(path: string, headers?: Record<string, string>): Promise<ApiResponse<T>> {
      const response = await app.inject({
        method: 'DELETE',
        url: path,
        headers,
      });

      return {
        status: response.statusCode,
        body: (response.json() || response.body) as T,
        headers: response.headers as Record<string, string>,
      };
    },
  };
}
