const People = require("../models/People"); const Credit = require("../models/Credit"); const Entry = require("../models/Entry"); const Media = require("../models/Media"); const { Op } = require("sequelize"); const { fetchPersonDetails: fetchPersonData } = require("./tmdbService"); const mediaDownloaderService = require("./mediaDownloaderService"); const { logToFile } = require("./logService"); const BadRequestError = require("../errors/BadRequestError"); const NotFoundError = require("../errors/NotFoundError"); const _mediaDownloaderService = mediaDownloaderService; class PeopleService { constructor() { if (!PeopleService.instance) { PeopleService.instance = this; } return PeopleService.instance; } async getAllPeople(includeCrew = false, { page, limit, search } = {}) { let where = { where: { cast_type: "cast", }, }; if (includeCrew) { where = {}; } const peopleWhere = {}; if (search) { peopleWhere.name = { [Op.like]: `%${search}%` }; } const queryOptions = { where: peopleWhere, order: [["popularity", "DESC"]], include: [ { model: Credit, as: "roles", include: { model: Entry, as: "entry", include: { model: Media, as: "medias" }, }, ...where, }, { model: Media, as: "medias" }, ], }; // If pagination params provided, use findAndCountAll if (page != null && limit != null) { queryOptions.limit = limit; queryOptions.offset = (page - 1) * limit; queryOptions.distinct = true; const { count, rows } = await People.findAndCountAll(queryOptions); return { data: rows, total: count, page, totalPages: Math.ceil(count / limit), }; } // Legacy: return plain array for backward compat const people = await People.findAll(queryOptions); return people; } async getPersonById(id) { const person = await People.findByPk(id, { include: [ { model: Credit, as: "roles", include: { model: Entry, as: "entry", include: { model: Media, as: "medias" }, }, }, { model: Media, as: "medias" }, ], }); if (!person) { throw new NotFoundError(`Person with ID ${id} not found`); } return person; } async getPersonByTmdbId(tmdbId) { const person = await People.findOne({ where: { tmdb_id: tmdbId }, include: [ { model: Credit, as: "roles", include: { model: Entry, as: "entry", include: { model: Media, as: "medias" }, }, }, { model: Media, as: "medias" }, ], }); return person; } async searchPeople(query) { const people = await People.findAll({ where: { name: { [Op.like]: `%${query}%` }, }, order: [["popularity", "DESC"]], limit: 20, include: [{ model: Media, as: "medias" }], }); return people; } async createPerson(personData) { try { const existingPerson = await People.findOne({ where: { tmdb_id: personData.tmdb_id }, }); if (existingPerson) { return existingPerson; } const person = await People.create(personData); return person; } catch (error) { logToFile(`Error creating person: ${error.message}`); throw error; } } async createOrUpdatePerson(personData) { return await People.findOrCreate({ where: { tmdb_id: personData.tmdb_id }, defaults: { name: personData.name, biography: personData.biography, birthday: personData.birthday, deathday: personData.deathday, place_of_birth: personData.place_of_birth, profile_path: personData.profile_path, popularity: personData.popularity, fully_fetched: true, last_fetch: new Date(), }, include: [ { model: Credit, as: "roles", include: { model: Entry, as: "entry", include: [{ model: Media, as: "medias" }], }, }, { model: Media, as: "medias" }, ], }); } async updatePerson(id, personData) { const person = await People.findByPk(id); if (!person) { throw new NotFoundError(`Person with ID ${id} not found`); } await person.update(personData); return await this.getPersonById(id); } async deletePerson(id) { const person = await People.findByPk(id); if (!person) { throw new NotFoundError(`Person with ID ${id} not found`); } await person.destroy(); return { success: true, message: `Person with ID ${id} was deleted` }; } async fetchAndSavePersonByTmdbId(tmdbId, options = {}) { if (!tmdbId) { throw new BadRequestError("TMDB ID is required"); } // Check if person already exists in database let person = await this.getPersonByTmdbId(tmdbId); if (person) { // If manually added (pinned), mark it if (options.pinned && !person.pinned) { await person.update({ pinned: true }); } // If person exists but hasn't been fully fetched, we'll update it if (!person.fully_fetched) { const personData = await fetchPersonData(tmdbId); if (personData) { person = await this.updatePerson(person.id, { ...personData, tmdb_id: tmdbId, fully_fetched: true, last_fetch: new Date(), }); // Download profile image if available if (personData.profile_path) { await _mediaDownloaderService.downloadPersonMedia(person); } } } return person; } // Fetch person data from TMDB const personData = await fetchPersonData(tmdbId); if (!personData) { throw new NotFoundError( `Person with TMDB ID ${tmdbId} not found in TMDB`, ); } // Create new person in database person = await this.createPerson({ ...personData, tmdb_id: tmdbId, fully_fetched: true, last_fetch: new Date(), pinned: !!options.pinned, }); // Download profile image if available if (personData.profile_path) { await _mediaDownloaderService.downloadPersonMedia(person); } return person; } } module.exports = new PeopleService();