const { Op } = require('sequelize'); const sequelize = require('../config/database'); const Entry = require('../models/Entry'); const EntryId = require('../models/EntryId'); const EntryRating = require('../models/EntryRating'); const EntrySeen = require('../models/EntrySeen'); const Episode = require('../models/Episode'); const EpisodeSeen = require('../models/EpisodeSeen'); const Season = require('../models/Season'); const Genre = require('../models/Genre'); const Collection = require('../models/Collection'); const Credit = require('../models/Credit'); const People = require('../models/People'); const Network = require('../models/Network'); const Media = require('../models/Media'); const asyncWrapper = require('../utils/asyncWrapper'); // ─── Shared Helper ────────────────────────────────────────────────────────── function formatEntryBrief(entry) { return { id: entry.id, title: entry.title, is_tvseries: entry.is_tvseries, poster_path: entry.poster_path, banner_path: entry.banner_path, runtime: entry.runtime, release_date: entry.release_date, is_favorite: entry.favorit, is_on_watchlist: entry.watchlist, rating: entry.entryRating || null, genres: entry.genres || [] }; } // ─── Controller ───────────────────────────────────────────────────────────── class AiQueryController { constructor() { if (!AiQueryController.instance) { AiQueryController.instance = this; } return AiQueryController.instance; } // ── Task 2: Recently Watched Movies ────────────────────────────────────── getRecentlyWatchedMovies = asyncWrapper(async (req, res) => { const limit = Math.min(parseInt(req.query.limit) || 10, 50); // Step 1: Get the last N EntrySeen IDs for movies (simple query, no genre joins) const seenIds = await EntrySeen.findAll({ attributes: ['id'], include: [{ model: Entry, as: 'entry', attributes: [], where: { is_tvseries: false, hidden: false } }], order: [['date_seen', 'DESC'], ['id', 'DESC']], limit }); if (seenIds.length === 0) { return res.status(200).json([]); } const idList = seenIds.map(s => s.id); // Step 2: Fetch full data for those IDs with all joins const entries = await EntrySeen.findAll({ where: { id: idList }, include: [{ model: Entry, as: 'entry', include: [ { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating', 'imdb_rating', 'rotten_tomatoes_rating'] }, { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } } ], attributes: ['id', 'title', 'is_tvseries', 'poster_path', 'banner_path', 'runtime', 'release_date', 'favorit', 'watchlist'] }], order: [['date_seen', 'DESC'], ['id', 'DESC']] }); const result = entries.map(es => ({ watch_id: es.id, date_watched: es.date_seen, seen_with: es.seen_with, accuracy: es.accuracy, entry: { id: es.entry.id, title: es.entry.title, poster_path: es.entry.poster_path, banner_path: es.entry.banner_path, runtime: es.entry.runtime, release_date: es.entry.release_date, is_favorite: es.entry.favorit, rating: es.entry.entryRating || null, genres: es.entry.genres || [] } })); res.status(200).json(result); }); // ── Task 3: Recently Watched Episodes ──────────────────────────────────── getRecentlyWatchedEpisodes = asyncWrapper(async (req, res) => { const limit = Math.min(parseInt(req.query.limit) || 10, 50); // Step 1: Get the last N EpisodeSeen IDs (simple query, no nested joins) const seenIds = await EpisodeSeen.findAll({ attributes: ['id'], include: [{ model: Episode, as: 'episode', attributes: [], include: [{ model: Season, as: 'season', attributes: [], include: [{ model: Entry, as: 'entry', attributes: [], where: { hidden: false } }] }] }], order: [['date_seen', 'DESC'], ['id', 'DESC']], limit }); if (seenIds.length === 0) { return res.status(200).json([]); } const idList = seenIds.map(s => s.id); // Step 2: Fetch full data for those IDs with all joins const records = await EpisodeSeen.findAll({ where: { id: idList }, include: [{ model: Episode, as: 'episode', attributes: ['id', 'name', 'episode_number', 'runtime', 'still_path', 'air_date'], include: [{ model: Season, as: 'season', attributes: ['id', 'name', 'season_number'], include: [{ model: Entry, as: 'entry', attributes: ['id', 'title', 'is_tvseries', 'poster_path', 'banner_path'], where: { hidden: false } }] }] }], order: [['date_seen', 'DESC'], ['id', 'DESC']] }); const result = records.map(es => ({ watch_id: es.id, date_watched: es.date_seen, seen_with: es.seen_with, episode: { id: es.episode.id, name: es.episode.name, episode_number: es.episode.episode_number, runtime: es.episode.runtime, still_path: es.episode.still_path, air_date: es.episode.air_date }, season: es.episode.season ? { id: es.episode.season.id, name: es.episode.season.name, season_number: es.episode.season.season_number } : null, series: es.episode.season && es.episode.season.entry ? { id: es.episode.season.entry.id, title: es.episode.season.entry.title, poster_path: es.episode.season.entry.poster_path } : null })); res.status(200).json(result); }); // ── Task 4: Watchlist ──────────────────────────────────────────────────── getWatchlist = asyncWrapper(async (req, res) => { const entries = await Entry.findAll({ where: { watchlist: true, hidden: false }, include: [ { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating', 'imdb_rating', 'rotten_tomatoes_rating'] }, { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } } ], order: [['updatedAt', 'DESC']] }); res.status(200).json(entries.map(formatEntryBrief)); }); // ── Task 5: Favorites ──────────────────────────────────────────────────── getFavorites = asyncWrapper(async (req, res) => { const entries = await Entry.findAll({ where: { favorit: true, hidden: false }, include: [ { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating', 'imdb_rating', 'rotten_tomatoes_rating'] }, { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } } ], order: [['updatedAt', 'DESC']] }); res.status(200).json(entries.map(formatEntryBrief)); }); // ── Task 6: Library Overview ───────────────────────────────────────────── getLibraryOverview = asyncWrapper(async (req, res) => { const [movieCount, seriesCount, totalEntries, movieWatchTime, seriesWatchTime, movieSeenCount, episodeSeenCount, genreCount] = await Promise.all([ Entry.count({ where: { is_tvseries: false, hidden: false } }), Entry.count({ where: { is_tvseries: true, hidden: false } }), Entry.count({ where: { hidden: false } }), EntrySeen.findOne({ include: [{ model: Entry, as: 'entry', attributes: [], where: { hidden: false } }], attributes: [[sequelize.fn('COALESCE', sequelize.fn('SUM', sequelize.col('runtime')), 0), 'totalMinutes']] }), EpisodeSeen.findOne({ include: [{ model: Episode, as: 'episode', attributes: [] }], attributes: [[sequelize.fn('COALESCE', sequelize.fn('SUM', sequelize.col('runtime')), 0), 'totalMinutes']] }), EntrySeen.count({ include: [{ model: Entry, as: 'entry', where: { hidden: false }, attributes: [] }] }), EpisodeSeen.count(), Entry.count({ distinct: true, include: [{ model: Genre, as: 'genres', attributes: [] }], attributes: [] }) ]); res.status(200).json({ total_entries: totalEntries, total_movies: movieCount, total_series: seriesCount, movies_watched_count: movieSeenCount, episodes_watched_count: episodeSeenCount, total_genres: genreCount, total_watch_time_minutes: { movies: parseInt(movieWatchTime.dataValues.totalMinutes) || 0, series: parseInt(seriesWatchTime.dataValues.totalMinutes) || 0 } }); }); // ── Task 7: Search Library ─────────────────────────────────────────────── searchLibrary = asyncWrapper(async (req, res) => { const { q, type, genre, watchlist, favorite } = req.query; const limit = Math.min(parseInt(req.query.limit) || 20, 100); const where = { hidden: false }; if (q) { where.title = { [Op.like]: `%${q}%` }; } if (type === 'movie') where.is_tvseries = false; if (type === 'series') where.is_tvseries = true; if (watchlist === 'true') where.watchlist = true; if (favorite === 'true') where.favorit = true; const entries = await Entry.findAll({ where, include: [ { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating', 'imdb_rating', 'rotten_tomatoes_rating'] }, { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } } ], order: [['title', 'ASC']], limit }); if (genre) { const filtered = entries.filter(e => e.genres.some(g => g.name.toLowerCase() === genre.toLowerCase()) ); return res.status(200).json(filtered.map(formatEntryBrief)); } res.status(200).json(entries.map(formatEntryBrief)); }); // ── Task 8: Upcoming ───────────────────────────────────────────────────── getUpcoming = asyncWrapper(async (req, res) => { const today = new Date(); const thirtyDaysLater = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000); const [upcomingMovies, nextEpisodes] = await Promise.all([ Entry.findAll({ where: { is_tvseries: false, release_date: { [Op.gte]: today }, hidden: false, showInCalendar: true }, attributes: ['id', 'title', 'release_date', 'poster_path', 'banner_path', 'runtime'], order: [['release_date', 'ASC']], limit: 20 }), Episode.findAll({ where: { air_date: { [Op.gte]: today, [Op.lte]: thirtyDaysLater } }, attributes: ['id', 'name', 'episode_number', 'air_date', 'still_path'], include: [{ model: Season, as: 'season', attributes: ['id', 'name', 'season_number', 'entry_id'], include: [{ model: Entry, as: 'entry', attributes: ['id', 'title', 'poster_path', 'is_tvseries'], where: { hidden: false, showInCalendar: true } }] }], order: [['air_date', 'ASC']], limit: 20 }) ]); res.status(200).json({ upcoming_movies: upcomingMovies.map(e => ({ id: e.id, title: e.title, release_date: e.release_date, poster_path: e.poster_path, banner_path: e.banner_path, runtime: e.runtime })), upcoming_episodes: nextEpisodes.map(ep => ({ id: ep.id, name: ep.name, episode_number: ep.episode_number, air_date: ep.air_date, still_path: ep.still_path, series_title: ep.season?.entry?.title, series_id: ep.season?.entry?.id, season_number: ep.season?.season_number, season_name: ep.season?.name })) }); }); // ── Task 9: Entry Detail ───────────────────────────────────────────────── getEntryDetail = asyncWrapper(async (req, res) => { const { id } = req.params; const entry = await Entry.findByPk(id, { include: [ { model: EntryId, as: 'entryId', attributes: { exclude: ['id', 'entry_id'] } }, { model: EntryRating, as: 'entryRating', attributes: { exclude: ['id', 'entry_id'] } }, { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } }, { model: Network, as: 'networks', attributes: ['id', 'name'], through: { attributes: [] } }, { model: Collection, as: 'collections', attributes: ['id', 'name', 'isUserCollection', 'description'], through: { attributes: [] } }, { model: Credit, as: 'credits', limit: 20, include: [{ model: People, as: 'person', attributes: ['id', 'name', 'profile_path', 'known_for_department'] }] }, { model: Season, as: 'seasons', include: [{ model: Episode, as: 'episodes', attributes: ['id', 'name', 'episode_number', 'runtime', 'air_date', 'still_path', 'overview'] }] }, { model: Media, as: 'medias', where: { isSelected: true }, required: false } ] }); if (!entry) { return res.status(404).json({ error: 'Entry not found' }); } // Also get watch history const watchHistory = await EntrySeen.findAll({ where: { entry_id: id }, order: [['date_seen', 'DESC']], limit: 50 }); const result = entry.toJSON(); result.watch_history = watchHistory; res.status(200).json(result); }); // ── Task 10: Genre Breakdown ───────────────────────────────────────────── getGenreBreakdown = asyncWrapper(async (req, res) => { const genres = await Genre.findAll({ include: [{ model: Entry, as: 'entries', attributes: ['id', 'runtime', 'is_tvseries'], through: { attributes: [] }, where: { hidden: false } }] }); const result = genres.map(g => ({ id: g.id, name: g.name, entry_count: g.entries.length, movie_count: g.entries.filter(e => !e.is_tvseries).length, series_count: g.entries.filter(e => e.is_tvseries).length })).filter(g => g.entry_count > 0) .sort((a, b) => b.entry_count - a.entry_count); res.status(200).json(result); }); // ── Task 11: All Collections ───────────────────────────────────────────── getAllCollections = asyncWrapper(async (req, res) => { const collections = await Collection.findAll({ attributes: ['id', 'name', 'description', 'isUserCollection', 'posterPath', 'backdropPath'], include: [{ model: Entry, as: 'entries', attributes: ['id'], through: { attributes: [] }, required: false }], order: [['name', 'ASC']] }); res.status(200).json(collections.map(c => ({ id: c.id, name: c.name, description: c.description, is_user_collection: c.isUserCollection, poster_path: c.posterPath, backdrop_path: c.backdropPath, entry_count: c.entries.length }))); }); // ── Task 12: Collection Detail ─────────────────────────────────────────── getCollectionDetail = asyncWrapper(async (req, res) => { const { id } = req.params; const collection = await Collection.findByPk(id, { include: [{ model: Entry, as: 'entries', through: { attributes: ['order'] }, include: [ { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating'] }, { model: Genre, as: 'genres', attributes: ['name'], through: { attributes: [] } } ] }] }); if (!collection) { return res.status(404).json({ error: 'Collection not found' }); } res.status(200).json(collection); }); // ── Task 13: In-Progress Series ────────────────────────────────────────── getInProgressSeries = asyncWrapper(async (req, res) => { const seriesWithSeen = await Entry.findAll({ where: { is_tvseries: true, hidden: false }, include: [ { model: EpisodeSeen, as: 'episodeSeens', attributes: [], required: true, duplicating: false }, { model: Season, as: 'seasons', include: [{ model: Episode, as: 'episodes', include: [{ model: EpisodeSeen, as: 'episodeSeens', attributes: ['id'], required: false }] }] }, { model: EntryRating, as: 'entryRating', attributes: ['user_rating'] } ], distinct: true }); const inProgress = seriesWithSeen .map(s => { const totalEpisodes = s.seasons?.reduce((sum, season) => sum + (season.episodes?.length || 0), 0) || 0; const seenEpisodes = s.seasons?.reduce((sum, season) => sum + (season.episodes?.reduce((es, ep) => es + ((ep.episodeSeens?.length || 0) > 0 ? 1 : 0), 0) || 0), 0) || 0; return { id: s.id, title: s.title, poster_path: s.poster_path, banner_path: s.banner_path, user_rating: s.entryRating?.user_rating || null, total_episodes: totalEpisodes, seen_episodes: seenEpisodes, progress_pct: totalEpisodes > 0 ? Math.round((seenEpisodes / totalEpisodes) * 100) : 0, is_complete: totalEpisodes > 0 && seenEpisodes >= totalEpisodes }; }) .filter(s => !s.is_complete && s.seen_episodes > 0) .sort((a, b) => b.progress_pct - a.progress_pct); res.status(200).json(inProgress); }); // ── Task 14: Watch Time Stats ──────────────────────────────────────────── getWatchTimeStats = asyncWrapper(async (req, res) => { const year = parseInt(req.query.year) || new Date().getFullYear(); const [totalMovieMinutes, totalEpisodeMinutes, monthlyMovieMinutes, monthlyEpisodeMinutes] = await Promise.all([ EntrySeen.findOne({ include: [{ model: Entry, as: 'entry', where: { hidden: false }, attributes: [] }], attributes: [[sequelize.fn('COALESCE', sequelize.fn('SUM', sequelize.col('runtime')), 0), 'total']] }), EpisodeSeen.findOne({ include: [{ model: Episode, as: 'episode', attributes: [] }], attributes: [[sequelize.fn('COALESCE', sequelize.fn('SUM', sequelize.col('runtime')), 0), 'total']] }), EntrySeen.findAll({ include: [{ model: Entry, as: 'entry', where: { hidden: false }, attributes: [] }], attributes: [ [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] ], where: sequelize.where(sequelize.fn('YEAR', sequelize.col('date_seen')), year), group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] }), EpisodeSeen.findAll({ include: [{ model: Episode, as: 'episode', attributes: [] }], attributes: [ [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] ], where: sequelize.where(sequelize.fn('YEAR', sequelize.col('date_seen')), year), group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] }) ]); const totalMovies = parseInt(totalMovieMinutes.dataValues.total) || 0; const totalEpisodes = parseInt(totalEpisodeMinutes.dataValues.total) || 0; const totalMinutes = totalMovies + totalEpisodes; const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; const monthlyMap = {}; for (let m = 1; m <= 12; m++) { monthlyMap[m] = { month: months[m - 1], movies: 0, episodes: 0, total: 0 }; } monthlyMovieMinutes.forEach(r => { const m = parseInt(r.dataValues.month); monthlyMap[m].movies = parseInt(r.dataValues.watchTime) || 0; }); monthlyEpisodeMinutes.forEach(r => { const m = parseInt(r.dataValues.month); monthlyMap[m].episodes = parseInt(r.dataValues.watchTime) || 0; }); const monthly = Object.values(monthlyMap).map(m => ({ ...m, total: m.movies + m.episodes })); res.status(200).json({ year, total_watch_time_minutes: totalMinutes, total_watch_time_hours: Math.round((totalMinutes / 60) * 10) / 10, movies_minutes: totalMovies, episodes_minutes: totalEpisodes, monthly }); }); // ── Task 15: Person Detail ─────────────────────────────────────────────── getPersonDetail = asyncWrapper(async (req, res) => { const { id } = req.params; const person = await People.findByPk(id, { include: [{ model: Credit, as: 'roles', include: [{ model: Entry, as: 'entry', attributes: ['id', 'title', 'is_tvseries', 'poster_path', 'release_date', 'favorit'], where: { hidden: false }, required: false }] }] }); if (!person) { return res.status(404).json({ error: 'Person not found' }); } res.status(200).json(person); }); } module.exports = new AiQueryController();