-- @query people_list
-- @db media 11.0
-- @with entity_filter
-- @param entity_ids TEXT
-- @end-with
SELECT
    rel.entityId AS entity_id,
    COUNT(DISTINCT rel.driveItemId) AS photo_count,
    COALESCE(re.isPinned, 0) AS is_pinned
FROM recognized_entity_lookup AS rel
JOIN media.media_properties AS cloud ON rel.driveItemId = cloud.driveItemId
JOIN media.media_libraries AS drive ON cloud.driveId = drive.driveId
LEFT JOIN media.recognized_entities AS re ON re.entityId = rel.entityId
WHERE cloud.isTombstoned = 0
  AND drive.libraryType = 'Gallery'
  AND cloud.takenDateTime IS NOT NULL
  AND cloud.photo IS NOT NULL
  AND cloud.video IS NULL
  -- @with entity_filter
  AND rel.entityId IN (SELECT value FROM json_each(?entity_ids))
  -- @end-with
GROUP BY rel.entityId
ORDER BY is_pinned DESC, photo_count DESC
