import type { DiffDeltaResponse } from "@/client";

export type DiffLineType = "addition" | "deletion" | "context";

export interface ProcessedDiffLine {
  lineNumber: number;
  type: DiffLineType;
  content: string;
}

export interface ProcessedFileData {
  filePath: string;
  lines: ProcessedDiffLine[];
  additionsCount: number;
  deletionsCount: number;
  isRename: boolean;
  isCopy: boolean;
  status: string;
}

const processDiffLines = (delta: DiffDeltaResponse): ProcessedDiffLine[] => {
  const lines: ProcessedDiffLine[] = [];

  for (const line of delta.lines ?? []) {
    const type: DiffLineType =
      line.origin === "+"
        ? "addition"
        : line.origin === "-"
          ? "deletion"
          : "context";

    const lineNumber = line.new_lineno ?? line.old_lineno ?? 0;
    lines.push({
      lineNumber,
      type,
      content: line.content,
    });
  }

  return lines.sort((a, b) => a.lineNumber - b.lineNumber);
};

export const processFileData = (
  delta: DiffDeltaResponse,
  index: number,
): ProcessedFileData => {
  const filePath = delta.new_file?.path || delta.old_file?.path || `file-${index}`;
  const lines = processDiffLines(delta);
  const additionsCount = delta.lines?.filter((l) => l.origin === "+").length ?? 0;
  const deletionsCount = delta.lines?.filter((l) => l.origin === "-").length ?? 0;

  return {
    filePath,
    lines,
    additionsCount,
    deletionsCount,
    isRename: delta.status === "renamed",
    isCopy: delta.status === "copied",
    status: delta.status,
  };
};

export const filterFiles = (
  files: ProcessedFileData[],
  searchTerm: string,
): ProcessedFileData[] => {
  if (!searchTerm.trim()) return files;
  const lower = searchTerm.toLowerCase();
  return files.filter((f) => f.filePath.toLowerCase().includes(lower));
};
