BEGIN;

ALTER TABLE config
	ALTER COLUMN normaluservotepoints SET DEFAULT 10,
	ALTER COLUMN followervotepoints SET DEFAULT 50,
	ALTER COLUMN subscribervotepoints SET DEFAULT 100,
	ALTER COLUMN title SET DEFAULT '{username}''s Learn Request Queue',
	ALTER COLUMN colors SET DEFAULT '{"bg": {"primary": "#444444","table": "#282828","navbar": "#666666","error": "#ff0000"},"fg": {"primary": "#dddddd","ahover": "#ffffff","title": "#eeeeee"}}',
	ADD COLUMN normaluserratelimit int NOT NULL DEFAULT 1,
	ADD COLUMN followerratelimit int NOT NULL DEFAULT 2,
	ADD COLUMN subscriberratelimit int NOT NULL DEFAULT 3;

CREATE OR REPLACE VIEW ratelimit_vw AS
	SELECT users.userid,COALESCE(count,0),ratelimit.reqcount AS max,COALESCE(count,0) >= ratelimit.reqcount AS status
		FROM users
		LEFT JOIN (SELECT requester,COUNT(url)
			FROM requests
			WHERE reqtimestamp > (now() - '24 hours'::interval)
			GROUP BY requests.requester
		) AS requests ON users.userid = requests.requester
		LEFT JOIN follows ON requests.requester = follows.userid
		LEFT JOIN subscriptions ON requests.requester = subscriptions.userid
		CROSS JOIN config
		CROSS JOIN LATERAL (VALUES (
			CASE
				WHEN follows.userid IS NULL AND subscriptions.userid IS NULL THEN config.normaluserratelimit
				WHEN follows.userid IS NOT NULL AND subscriptions.userid IS NULL THEN config.followerratelimit
				WHEN subscriptions.userid IS NOT NULL THEN config.subscriberratelimit
			END
		)) AS ratelimit(reqcount);


ROLLBACK;
--COMMIT;
