import * as git from 'git-rev-sync';

/**
 * Vite plugin to generate a version string from Git info.
 * Format: {COMMIT_DATE}.{REPOSITORY_NAME}.{BRANCH_NAME}+{COMMIT_ID}
 */
export default function retrieveGitVersion(repositoryName: string) {
  let versionString = '';

  return {
    name: 'retrieve-git-version',

    buildStart() {
      versionString = generateVersionString(repositoryName);
      console.log('Generated version:', versionString);
    },

    config() {
      return {
        define: {
          __APP_VERSION__: JSON.stringify(
            versionString || generateVersionString(repositoryName)
          ),
        },
      };
    },
  };
}

/**
 * Generates a version string from Git info using git-rev-sync.
 */
function generateVersionString(repositoryName: string) {
  let versionString = '';

  let date: Date;
  try {
    date = git.date();
  } catch {
    // Fallback to current date
    date = new Date();
  }
  versionString += `${date.toISOString().split('T')[0]}`;

  versionString += `.${repositoryName}`;

  try {
    const branch = git.branch('./');
    if (branch) {
      versionString += `.${branch}`;
    }
  } catch {
    /* empty */
  }

  try {
    const commitId = git.short('./');
    if (commitId) {
      versionString += `+${commitId}`;
    }
  } catch {
    /* empty */
  }

  return versionString;
}
