import { ApiError, request } from './client';

export type ReaderMode = 'single' | 'continuous';
export type ReaderPageGap = 'none' | 'small' | 'medium' | 'large';

export type Preferences = {
    reader_mode: ReaderMode;
    reader_page_gap: ReaderPageGap;
    updated_at: string;
};

/**
 * Maps a named gap option to a CSS pixel value. Centralised here so the
 * settings UI, the reader, and any future surfaces all show the same
 * spacing.
 */
export const GAP_PX: Record<ReaderPageGap, number> = {
    none: 0,
    small: 12,
    medium: 32,
    large: 64
};

/**
 * Returns the current user's stored reader preferences, or `null` if there
 * is no valid session. Anything other than 401 is re-thrown so the caller
 * can surface real errors.
 */
export async function getPreferences(): Promise<Preferences | null> {
    try {
        return await request<Preferences>('/v1/auth/me/preferences');
    } catch (e) {
        if (e instanceof ApiError && e.status === 401) return null;
        throw e;
    }
}

/**
 * Partially updates the user's reader preferences. Unspecified fields are
 * left unchanged on the server.
 */
export async function updatePreferences(
    patch: Partial<Pick<Preferences, 'reader_mode' | 'reader_page_gap'>>
): Promise<Preferences> {
    return request<Preferences>('/v1/auth/me/preferences', {
        method: 'PATCH',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(patch)
    });
}
