import type { GqlAuthParam, Headers } from '../types';

// Create headers factory function
export function createHeadersFactory(
  args?: Pick<
    GqlAuthParam,
    'headers' | 'secret' | 'accessToken' | 'auditUserId'
  >
) {
  return async (base?: Headers): Promise<Headers> => {
    const result: Record<string, string> = {};

    // Add static or function headers
    if (args?.headers) {
      if (typeof args.headers === 'function') {
        const functionResult = await args.headers();
        for (const key in functionResult) {
          result[key] = functionResult[key];
        }
      } else {
        for (const key in args.headers) {
          result[key] = args.headers[key];
        }
      }
    }

    // Add base headers
    if (base) {
      for (const key in base) {
        result[key] = base[key];
      }
    }

    // Add auth headers
    if (args?.secret) {
      result['x-hasura-admin-secret'] = args.secret;
    } else if (args?.accessToken) {
      result.authorization = args.accessToken.startsWith('Bearer ')
        ? args.accessToken
        : `Bearer ${args.accessToken}`;
    }

    if (args?.auditUserId) {
      result['x-hasura-audit-user-id'] = args.auditUserId;
    }

    return result;
  };
}

export type HeadersFactory = ReturnType<typeof createHeadersFactory>;
