import { PieceAuth } from '@activepieces/pieces-framework';

/**
 * Authentication for CrowdStrike Falcon API
 * Supports custom authentication for MSSP scenarios with environment-specific configurations
 */
export const crowdstrikeAuth = PieceAuth.CustomAuth({
  props: {
    base_url: PieceAuth.SecretText({
      displayName: 'API Base URL',
      description: 'The base URL for your CrowdStrike API (e.g., https://api.crowdstrike.com)',
      required: true,
    }),
    client_id: PieceAuth.SecretText({
      displayName: 'Client ID',
      description: 'Your CrowdStrike API client ID',
      required: true,
    }),
    client_secret: PieceAuth.SecretText({
      displayName: 'Client Secret',
      description: 'Your CrowdStrike API client secret',
      required: true,
    }),
  },
  required: true,
  
  // Validate authentication by attempting to get an access token
  async validate({ auth }) {
    try {
      const tokenResponse = await getAccessToken(auth);
      return tokenResponse.success;
    } catch (error) {
      return false;
    }
  }
});

/**
 * Get an OAuth2 access token from CrowdStrike API
 * @param auth Authentication parameters
 * @returns Access token response
 */
export async function getAccessToken(auth: {
  base_url: string;
  client_id: string;
  client_secret: string;
}) {
  const url = `${auth.base_url}/oauth2/token`;
  
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json',
    },
    body: new URLSearchParams({
      'client_id': auth.client_id,
      'client_secret': auth.client_secret,
      'grant_type': 'client_credentials'
    })
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Failed to get access token: ${response.status} ${errorText}`);
  }

  const data = await response.json();
  
  return {
    success: true,
    access_token: data.access_token,
    token_type: data.token_type,
    expires_in: data.expires_in
  };
}
