import log from 'electron-log';
import { checkGemrcStatus, createGemrc, updateGemrc, GemrcConfig } from './gemrc-manager';
import { setupNpmrc, checkNpmrcStatus } from './npmrc-manager';

export interface ArtifactoryStatus {
  configured: boolean;
  gemrcExists: boolean;
  npmrcConfigured: boolean;
  username?: string;
  token?: string;
  credentialsValid?: boolean;
  credentialsValidationError?: string;
  details?: GemrcConfig;
}

export interface ArtifactorySetupOptions {
  username: string;
  token: string;
  overwrite?: boolean;
}

export interface InstallResult {
  success: boolean;
  message: string;
}

/**
 * Check the current Artifactory configuration status
 */
export async function checkArtifactoryStatus(): Promise<ArtifactoryStatus> {
  try {
    const [gemrcStatus, npmrcStatus] = await Promise.all([
      checkGemrcStatus(),
      checkNpmrcStatus()
    ]);

    return {
      configured: gemrcStatus.configured && npmrcStatus.configured,
      gemrcExists: gemrcStatus.exists,
      npmrcConfigured: npmrcStatus.configured,
      username: gemrcStatus.username,
      token: gemrcStatus.token,
      credentialsValid: gemrcStatus.credentialsValid,
      credentialsValidationError: gemrcStatus.credentialsValidationError,
      details: gemrcStatus
    };
  } catch (error: any) {
    log.error('Error checking Artifactory status:', error);
    return {
      configured: false,
      gemrcExists: false,
      npmrcConfigured: false
    };
  }
}

/**
 * Setup Artifactory credentials in .gemrc
 */
export async function setupArtifactory(options: ArtifactorySetupOptions): Promise<InstallResult> {
  try {
    log.info('Setting up Artifactory credentials');

    // Validate inputs
    if (!options.username || !options.token) {
      return {
        success: false,
        message: 'Username and token are required'
      };
    }

    const status = await checkGemrcStatus();

    if (status.exists && !options.overwrite) {
      // Update existing .gemrc
      await updateGemrc(options.username, options.token);
    } else {
      // Create new .gemrc
      await createGemrc(options.username, options.token);
    }

    log.info('Artifactory credentials saved to .gemrc');

    // Also save the token to ~/.npmrc for pnpm @inst registry access
    const npmrcResult = await setupNpmrc({ token: options.token });
    if (npmrcResult.success) {
      log.info('Artifactory token saved to .npmrc');
    } else {
      log.warn('Failed to save token to .npmrc:', npmrcResult.message);
    }

    return {
      success: true,
      message: 'Artifactory credentials saved successfully'
    };
  } catch (error: any) {
    log.error('Failed to setup Artifactory:', error);
    return {
      success: false,
      message: `Failed: ${error.message}`
    };
  }
}
