import { ProjectJsonFile } from '../core/project';
import { ALWAYSAI_DO_NOT_TRACK } from '../environment';
import { CliAuthenticationClient } from './authentication-client';

import { version } from '../version';

const writeKey = 'H9SHsAseGIYI6PjjNhBO6OSyzx4cJSUG:';
const buffer = Buffer.from(writeKey, 'utf8');
const authHeader = buffer.toString('base64');

export async function postTrackingDataToSegment(event: string, label?: any) {
  if (ALWAYSAI_DO_NOT_TRACK) {
    return;
  }

  let uuid = 'undefined';
  let projectId = '';
  try {
    ({ uuid } = await CliAuthenticationClient({ readonly: true }).getInfo());
    projectId = event.split('project ')[1];

    if (!projectId) {
      const projectJsonFile = ProjectJsonFile();
      const project = projectJsonFile.read().project;

      if (projectJsonFile.exists()) {
        if (project) {
          projectId = project.id;
        }
      }
    }
  } catch {
    // empty
  }

  const data = {
    event,
    userId: uuid,
    properties: {
      category: 'CLI',
      label,
      context: { direct: true },
      version: version,
      projectId
    }
  };
  try {
    await fetch('https://api.segment.io/v1/track', {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Basic ${authHeader}`
      }
    });
  } catch {
    // empty
  }
}
