/**
 * Shared converter types and utilities.
 *
 * Used by both rDocs and rNotes converter systems.
 * Source-specific converters implement NoteConverter.
 * ConvertedNote is the intermediate format between external sources and NoteItem.
 */

import type { NoteItem, SourceRef } from '../../modules/rnotes/schemas';

// Re-export schema types that converters need
export type { NoteItem, SourceRef };

// ── Shared utilities ──

/** Hash content for conflict detection (shared across all converters). */
export function hashContent(content: string): string {
	let hash = 0;
	for (let i = 0; i < content.length; i++) {
		const char = content.charCodeAt(i);
		hash = ((hash << 5) - hash) + char;
		hash |= 0;
	}
	return Math.abs(hash).toString(36);
}

// ── Shared types ──

export interface ConvertedNote {
	title: string;
	content: string;           // TipTap JSON string
	contentPlain: string;      // Plain text for search
	markdown: string;          // Original/generated markdown (for canvas shapes)
	tags: string[];
	sourceRef: SourceRef;
	/** Optional note type override */
	type?: NoteItem['type'];
	/** Extracted attachments (images, etc.) — saved to /data/files/uploads/ */
	attachments?: { filename: string; data: Uint8Array; mimeType: string }[];
}

export interface ImportResult {
	notes: ConvertedNote[];
	notebookTitle: string;
	warnings: string[];
}

export interface ExportResult {
	data: Uint8Array;
	filename: string;
	mimeType: string;
}

export interface NoteConverter {
	id: string;
	name: string;
	requiresAuth: boolean;

	/** Import from external source into ConvertedNote[] */
	import(input: ImportInput): Promise<ImportResult>;

	/** Export NoteItems to external format */
	export(notes: NoteItem[], opts: ExportOptions): Promise<ExportResult>;
}

export interface ImportInput {
	/** ZIP file data for file-based sources (Logseq, Obsidian) */
	fileData?: Uint8Array;
	/** Page/doc IDs for API-based sources (Notion, Google Docs) */
	pageIds?: string[];
	/** Whether to import recursively (sub-pages) */
	recursive?: boolean;
	/** Access token for authenticated sources */
	accessToken?: string;
}

export interface ExportOptions {
	/** Notebook title for the export */
	notebookTitle?: string;
	/** Access token for authenticated sources */
	accessToken?: string;
	/** Target parent page/folder ID for API-based exports */
	parentId?: string;
}
