/**
 * execute.ts — Execution logic. Imports from ../lib/. NO validation.
 * Receives validated data, returns typed result.
 */
import { existsSync } from 'fs';
import { join } from 'path';
import type { AbortSpec, AbortResult } from './types.js';
import { execGit } from '../lib/git.js';

export async function execute(spec: AbortSpec, workDir: string = process.cwd()): Promise<AbortResult> {
  try {
    // Detect which operation is in progress
    const gitDir = join(workDir, '.git');
    const rebaseMergeDir = join(gitDir, 'rebase-merge');
    const rebaseApplyDir = join(gitDir, 'rebase-apply');
    const mergeHeadFile = join(gitDir, 'MERGE_HEAD');
    const cherryPickHeadFile = join(gitDir, 'CHERRY_PICK_HEAD');

    let operation: 'rebase' | 'merge' | 'cherry-pick' | 'none' = 'none';
    let restored = false;

    if (spec.git) {
      // Check for rebase
      if (existsSync(rebaseMergeDir) || existsSync(rebaseApplyDir)) {
        operation = 'rebase';
        const result = await execGit(['rebase', '--abort'], workDir);
        restored = result.exitCode === 0;
      }
      // Check for merge
      else if (existsSync(mergeHeadFile)) {
        operation = 'merge';
        const result = await execGit(['merge', '--abort'], workDir);
        restored = result.exitCode === 0;
      }
      // Check for cherry-pick
      else if (existsSync(cherryPickHeadFile)) {
        operation = 'cherry-pick';
        const result = await execGit(['cherry-pick', '--abort'], workDir);
        restored = result.exitCode === 0;
      }
    }

    return {
      success: operation === 'none' || restored,
      operation,
      restored,
      message: operation === 'none'
        ? 'No in-progress operation detected'
        : restored
          ? `${operation} aborted successfully`
          : `Failed to abort ${operation}`,
    };
  } catch (err) {
    return {
      success: false,
      operation: 'none',
      restored: false,
      error: (err as Error).message,
    };
  }
}
