import { type Attributes, Extension } from '@tiptap/core'
import '@tiptap/extension-text-style'

declare module '@tiptap/core' {
	interface Commands<ReturnType> {
		fontSize: {
			setFontSize: (size: string) => ReturnType
			unsetFontSize: () => ReturnType
		}
	}
}

export const FontSize = Extension.create({
	name: 'fontSize',

	addOptions() {
		return {
			types: ['textStyle']
		}
	},

	addGlobalAttributes() {
		return [
			{
				types: ['paragraph'],
				attributes: {
					class: {}
				}
			},
			{
				types: this.options.types,
				attributes: {
					fontSize: {
						parseHTML: (element) => element.style.fontSize.replace(/['"]+/g, ''),
						renderHTML: (attributes) => {
							if (!attributes.fontSize) {
								return {}
							}

							return {
								style: `font-size: ${attributes.fontSize}`
							}
						}
					}
				} as Attributes
			}
		]
	},

	addCommands() {
		return {
			setFontSize:
				(fontSize: string) =>
				({ chain }) =>
					chain().setMark('textStyle', { fontSize }).run(),
			unsetFontSize:
				() =>
				({ chain }) =>
					chain().setMark('textStyle', { fontSize: null }).removeEmptyTextStyle().run()
		}
	}
})

export default FontSize
