DROP FUNCTION IF EXISTS most_recent_comments(integer);
DROP VIEW IF EXISTS patch_comment_view;
DROP VIEW IF EXISTS patch_view;
DROP VIEW IF EXISTS commitfest_view;

CREATE OR REPLACE VIEW commitfest_view AS
SELECT
	v.id, v.name, v.commitfest_status_id, s.name AS commitfest_status
FROM
	commitfest v
	INNER JOIN commitfest_status s ON v.commitfest_status_id = s.id;

CREATE OR REPLACE VIEW patch_view AS
SELECT v.id, v.commitfest_topic_id, s.name AS commitfest_topic,
	s.sortorder AS commitfest_topic_sortorder,
	s.commitfest_id, f.name AS commitfest, v.name,
	v.patch_status_id, ps.name AS patch_status, v.author, v.reviewers,
	v.committer, v.date_closed, v.creation_time
FROM
	patch v
	INNER JOIN commitfest_topic s ON v.commitfest_topic_id = s.id
	INNER JOIN commitfest f ON s.commitfest_id = f.id
	INNER JOIN patch_status ps ON v.patch_status_id = ps.id;

CREATE OR REPLACE VIEW patch_comment_view AS
SELECT
	v.id, v.patch_id, p.name AS patch_name, v.patch_comment_type_id,
	pct.name AS patch_comment_type, v.message_id, v.content, v.creator,
	v.creation_time
FROM
	patch_comment v
	INNER JOIN patch_comment_type pct ON v.patch_comment_type_id = pct.id
	INNER JOIN patch p ON v.patch_id = p.id;

CREATE OR REPLACE VIEW commitfest_activity_log AS
SELECT v.activity_id, v.commitfest_id, v.last_updated_time, v.last_updater,
	v.original_name AS patch_name,
	p.id AS patch_id,
	CASE WHEN v.change_type = 'INSERT' THEN 'New Patch'
		 WHEN v.change_type = 'UPDATE' THEN 'Patch Edited'
		 WHEN v.change_type = 'DELETE' THEN 'Patch Deleted'
	END AS activity_type,
	patch_audit_details(v) AS details
FROM
	patch_audit v
	LEFT JOIN patch p ON v.patch_id = p.id
UNION ALL
SELECT v.activity_id, v.commitfest_id, v.last_updated_time, v.last_updater,
	v.patch_name, v.patch_id,
	CASE WHEN v.change_type = 'INSERT' THEN 'New Comment'
	     WHEN v.change_type = 'UPDATE' THEN 'Edit Comment'
	     WHEN v.change_type = 'DELETE' THEN 'Delete Comment'
	END AS activity_type,
	patch_comment_audit_details(v) AS details
FROM
	patch_comment_audit v
	LEFT JOIN patch p ON v.patch_id = p.id;
