/**
 * Preview Worktree Helper
 *
 * Creates and removes git worktrees for preview deployments.
 * Preview mode checks out a specific branch into a temp directory
 * so the Docker build runs against the correct code.
 */

import { simpleGit } from 'simple-git';
import { createModuleLogger } from '../logger/index.js';

const log = createModuleLogger('preview:worktree');

/**
 * Create a git worktree at the specified destination, checking out the given branch.
 * Does NOT create a new branch — the branch must already exist.
 *
 * @param repoPath - Path to the git repository (bare clone)
 * @param branch - Branch to check out
 * @param destPath - Where to create the worktree
 */
export async function createPreviewWorktree(
  repoPath: string,
  branch: string,
  destPath: string,
): Promise<void> {
  log.info({ repoPath, branch, destPath }, 'creating preview worktree');
  const git = simpleGit(repoPath);
  await git.raw(['worktree', 'add', destPath, branch]);
}

/**
 * Remove a git worktree.
 *
 * @param repoPath - Path to the git repository
 * @param worktreePath - Path of the worktree to remove
 */
export async function removePreviewWorktree(
  repoPath: string,
  worktreePath: string,
): Promise<void> {
  log.info({ repoPath, worktreePath }, 'removing preview worktree');
  try {
    const git = simpleGit(repoPath);
    await git.raw(['worktree', 'remove', worktreePath, '--force']);
  } catch (error) {
    log.warn({ worktreePath, err: error }, 'failed to remove worktree (may not exist)');
  }
}
