import { SF_STALE_STATE, SFError } from "../errors.js";
import { logWarning } from "../workflow-logger.js";
import { _getAdapter, rowToArtifact } from "./sf-db-core.js";

export function clearArtifacts() {
	const currentDb = _getAdapter();
	if (!currentDb) return;
	try {
		currentDb.exec("DELETE FROM artifacts");
	} catch (e) {
		logWarning("db", `clearArtifacts failed: ${e.message}`);
	}
}

export function insertArtifact(a) {
	const currentDb = _getAdapter();
	if (!currentDb) throw new SFError(SF_STALE_STATE, "sf-db: No database open");
	currentDb
		.prepare(`INSERT OR REPLACE INTO artifacts (path, artifact_type, milestone_id, slice_id, task_id, full_content, imported_at)
     VALUES (:path, :artifact_type, :milestone_id, :slice_id, :task_id, :full_content, :imported_at)`)
		.run({
			":path": a.path,
			":artifact_type": a.artifact_type,
			":milestone_id": a.milestone_id,
			":slice_id": a.slice_id,
			":task_id": a.task_id,
			":full_content": a.full_content,
			":imported_at": new Date().toISOString(),
		});
}

export function getArtifact(path) {
	const currentDb = _getAdapter();
	if (!currentDb) return null;
	const row = currentDb
		.prepare("SELECT * FROM artifacts WHERE path = :path")
		.get({ ":path": path });
	if (!row) return null;
	return rowToArtifact(row);
}

export function deleteArtifactByPath(path) {
	const currentDb = _getAdapter();
	if (!currentDb) throw new SFError(SF_STALE_STATE, "sf-db: No database open");
	currentDb
		.prepare("DELETE FROM artifacts WHERE path = :path")
		.run({ ":path": path });
}
