CREATE TABLE login (
	username   text        NOT NULL UNIQUE,
	pass       text,
	email      text,
	fullname   text,
	editlang   text[],
	id         integer     NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
);

CREATE TABLE word (
	form       text,
	alt        text[],
	lang       text                 DEFAULT 'en',
	cat        integer              REFERENCES word (id),
	ref        integer              REFERENCES word (id),
	prio       smallint             DEFAULT '1'
	                                CHECK (prio >= 0 OR ref IS NOT NULL),
	grade      integer,
	cover      boolean     NOT NULL DEFAULT FALSE,
	image      jsonb                CHECK (image->>'source' ~ '^https?://'
	                                   AND jsonb_typeof(image->'convert') = 'array'),
	wptitle    text,
	story      text,
	creator    integer              REFERENCES login (id),
	created    timestamptz          DEFAULT now(),
	updated    timestamptz,
	id         integer     NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
);

COMMENT ON COLUMN word.form       IS 'preferred textual representation';
COMMENT ON COLUMN word.alt        IS 'alternate forms with equivalent meaning';
COMMENT ON COLUMN word.lang       IS 'ISO 639 language code matching wikipedia subdomain';
COMMENT ON COLUMN word.cat        IS 'primary hierarchical classification';
COMMENT ON COLUMN word.ref        IS 'reference to equivalent en translation';
COMMENT ON COLUMN word.prio       IS 'difficulty level or importance; lower values have precedence';
COMMENT ON COLUMN word.grade      IS 'ascending hierarchical order, preceding default alphabetical';
COMMENT ON COLUMN word.cover      IS 'highlight if selected';
COMMENT ON COLUMN word.image      IS 'metadata of illustrations, including downloaded URI and ImageMagick convert options';
COMMENT ON COLUMN word.wptitle    IS 'reference Wikipedia article';
COMMENT ON COLUMN word.story      IS 'paragraph defining or describing the entity, wikipedia intro';
COMMENT ON COLUMN word.updated    IS 'last significant change';
COMMENT ON COLUMN word.creator    IS 'user responsible for initial submit';

CREATE TABLE kind (
	word       integer     NOT NULL REFERENCES word (id),
	cat        integer     NOT NULL REFERENCES word (id),
	                                UNIQUE (word, cat),
	truth      smallint    NOT NULL DEFAULT '50',
	creator    integer              REFERENCES login (id),
	created    timestamptz          DEFAULT now(),
	updated    timestamptz,
	id         integer     NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
);

COMMENT ON COLUMN kind.truth      IS 'link validity ranging from 0 (never) to 100 (always)';

CREATE OR REPLACE VIEW _word_ref AS
	SELECT
		r.form, r.alt, r.lang,
		coalesce(r.cat,     w.cat    ) cat, --TODO translate w?
		coalesce(r.ref,     r.id     ) "ref",
		coalesce(r.prio,    w.prio   ) prio,
		coalesce(r.grade,   w.grade  ) grade,
		coalesce(r.cover,   w.cover  ) cover,
		coalesce(r.image,   w.image  ) image,
		coalesce(r.wptitle, w.wptitle) wptitle,
		coalesce(r.story,   w.story  ) story,
		r.creator, r.created, r.updated,
		CASE WHEN nullif(r.image, '{}') IS NOT NULL THEN r.id
		     WHEN nullif(w.image, '{}') IS NOT NULL THEN w.id END id -- image id
	FROM word r
	LEFT JOIN word w ON w.id = r.ref;

CREATE OR REPLACE VIEW _word_tree AS
	WITH RECURSIVE r AS (
		SELECT w.ref, w.lang, w.cat, w.grade, w.form, NULL::int trans
		FROM _word_ref w
	UNION ALL
		SELECT r.ref, r.lang, w.cat,
			CASE WHEN w.lang=r.lang OR t.lang=r.lang THEN r.grade ELSE w.grade END,
			CASE WHEN w.lang=r.lang OR t.lang=r.lang THEN r.form ELSE w.form END,
			CASE WHEN w.lang=r.lang OR t.lang=r.lang THEN w.id END
		FROM r JOIN word w ON w.id = r.cat
		  LEFT JOIN word t ON w.id = t.ref AND t.lang = r.lang
		WHERE r.trans IS NULL
	)
	SELECT ref, lang, trans cat, grade, form FROM r WHERE trans IS NOT NULL
		ORDER BY cat, grade, form, ref;

CREATE OR REPLACE VIEW _word AS
	SELECT
		(SELECT array_agg(coalesce(ref, id)) FROM _word_tree
			WHERE cat = w.ref AND lang = w.lang) sub,
		w.*
	FROM _word_ref w
	;
