-- NOTE: must update MERGED_SOURCE_ID (6969) here
CREATE VIEW updatesView AS
SELECT
    mangas._id AS mangaId,
    mangas.title AS mangaTitle,
    chapters._id AS chapterId,
    chapters.name AS chapterName,
    chapters.scanlator,
    chapters.url AS chapterUrl,
    chapters.read,
    chapters.bookmark,
    chapters.last_page_read,
    mangas.source,
    mangas.favorite,
    mangas.thumbnail_url AS thumbnailUrl,
    mangas.cover_last_modified AS coverLastModified,
    chapters.date_upload AS dateUpload,
    chapters.date_fetch AS datefetch,
    excluded_scanlators.scanlator AS excludedScanlator
FROM mangas JOIN chapters
ON mangas._id = chapters.manga_id
LEFT JOIN excluded_scanlators
ON mangas._id = excluded_scanlators.manga_id
AND chapters.scanlator = excluded_scanlators.scanlator
WHERE favorite = 1 AND source <> 6969
AND date_fetch > date_added
UNION
SELECT
    mangas._id AS mangaId,
    mangas.title AS mangaTitle,
    chapters._id AS chapterId,
    chapters.name AS chapterName,
    chapters.scanlator,
    chapters.url AS chapterUrl,
    chapters.read,
    chapters.bookmark,
    chapters.last_page_read,
    mangas.source,
    mangas.favorite,
    mangas.thumbnail_url AS thumbnailUrl,
    mangas.cover_last_modified AS coverLastModified,
    chapters.date_upload AS dateUpload,
    chapters.date_fetch AS datefetch,
    excluded_scanlators.scanlator AS excludedScanlator
FROM mangas
LEFT JOIN (
    SELECT merged.manga_id,merged.merge_id
    FROM merged
    GROUP BY merged.merge_id
) AS ME
ON ME.merge_id = mangas._id
JOIN chapters
ON ME.manga_id = chapters.manga_id
LEFT JOIN excluded_scanlators
ON mangas._id = excluded_scanlators.manga_id
AND chapters.scanlator = excluded_scanlators.scanlator
WHERE favorite = 1 AND source = 6969
AND date_fetch > date_added
ORDER BY datefetch DESC;

getRecentUpdates:
SELECT *
FROM updatesView
WHERE dateUpload > :after
LIMIT :limit;

getRecentUpdatesWithFilters:
SELECT *
FROM updatesView
WHERE dateUpload > :after
AND (:read IS NULL OR read = :read)
-- Started means some progress but not finished, Read means finished chapter, thus:
AND (
    :started IS NULL
    OR (:started = 1 AND last_page_read > 0 AND read = 0)
    OR (:started = 0 AND last_page_read = 0 AND read = 0)
)
AND (:bookmarked IS NULL OR bookmark = :bookmarked)
AND (
    (excludedScanlator IS NULL OR :hideExcludedScanlators = 0)
)
LIMIT :limit;

getUpdatesByReadStatus:
SELECT *
FROM updatesView
WHERE read = :read
AND dateUpload > :after
LIMIT :limit;
