/**
 * rPubs Automerge document schemas.
 *
 * Granularity: one Automerge document per draft.
 * DocId format: {space}:pubs:drafts:{draftId}
 */

import type { DocSchema } from '../../shared/local-first/document';

// ── Document types ──

export interface PubsDraftMeta {
	id: string;
	title: string;
	author: string;
	format: string;       // selected book format id
	createdAt: number;
	updatedAt: number;
}

export interface PubsDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	draft: PubsDraftMeta;
	content: string;       // markdown content (Automerge text)
}

// ── Schema registration ──

export const pubsDraftSchema: DocSchema<PubsDoc> = {
	module: 'pubs',
	collection: 'drafts',
	version: 1,
	init: (): PubsDoc => ({
		meta: {
			module: 'pubs',
			collection: 'drafts',
			version: 1,
			spaceSlug: '',
			createdAt: Date.now(),
		},
		draft: {
			id: '',
			title: '',
			author: '',
			format: 'digest',
			createdAt: Date.now(),
			updatedAt: Date.now(),
		},
		content: '',
	}),
	migrate: (doc: PubsDoc, _fromVersion: number): PubsDoc => doc,
};

// ── Helpers ──

/** Generate a docId for a draft. */
export function pubsDocId(space: string, draftId: string) {
	return `${space}:pubs:drafts:${draftId}` as const;
}
