'use strict'; const FACE_REF_TABLES = ['student_face_refs', 'photo_faces']; function isFaceTable(table) { return FACE_REF_TABLES.includes(table); } async function findBrokenFaceRefs(pool, storage, { studentId, limit } = {}) { const results = []; for (const table of FACE_REF_TABLES) { let sql; const params = []; if (table === 'student_face_refs') { sql = `SELECT id, photo_path, student_id FROM student_face_refs WHERE photo_path IS NOT NULL AND photo_path <> ''`; if (studentId) { sql += ` AND student_id = $${params.length + 1}`; params.push(studentId); } } else { sql = `SELECT id, photo_path, student_id FROM photo_faces WHERE photo_path IS NOT NULL AND photo_path <> ''`; if (studentId) { sql += ` AND student_id = $${params.length + 1}`; params.push(studentId); } } sql += ` ORDER BY id`; if (limit) { sql += ` LIMIT $${params.length + 1}`; params.push(limit); } const { rows } = await pool.query(sql, params); for (const row of rows) { const key = storage.keyFromPath(row.photo_path); if (!key) continue; const exists = await storage.exists(key); if (!exists) { results.push({ table, id: row.id, photo_path: row.photo_path, student_id: row.student_id }); } } } return results; } async function scanAllBrokenFaceRefs(pool, storage, { limit } = {}) { const results = []; for (const table of FACE_REF_TABLES) { let sql; const params = []; if (table === 'student_face_refs') { sql = `SELECT id, photo_path, student_id FROM student_face_refs WHERE photo_path IS NOT NULL AND photo_path <> ''`; } else { sql = `SELECT id, photo_path, student_id FROM photo_faces WHERE photo_path IS NOT NULL AND photo_path <> ''`; } sql += ` ORDER BY id`; if (limit) { sql += ` LIMIT $${params.length + 1}`; params.push(limit); } const { rows } = await pool.query(sql, params); for (const row of rows) { const key = storage.keyFromPath(row.photo_path); if (!key) continue; const exists = await storage.exists(key); if (!exists) { results.push({ table, id: row.id, photo_path: row.photo_path, student_id: row.student_id }); } } } return results; } async function cleanupAllBrokenFaceRefs(pool, storage, { limit } = {}) { const broken = await scanAllBrokenFaceRefs(pool, storage, { limit }); let deleted = 0; const errors = []; for (const item of broken) { try { await deleteFaceRef(pool, storage, { table: item.table, id: item.id }); deleted++; } catch (e) { errors.push({ table: item.table, id: item.id, error: e.message }); } } return { broken, deleted, total: broken.length, errors }; } async function deleteFaceRef(pool, storage, { table, id }) { if (!isFaceTable(table)) { throw new Error('Недопустимая таблица'); } const { rows } = await pool.query( `DELETE FROM ${table} WHERE id = $1 RETURNING id, photo_path`, [id] ); return rows[0] || null; } module.exports = { findBrokenFaceRefs, scanAllBrokenFaceRefs, cleanupAllBrokenFaceRefs, deleteFaceRef, FACE_REF_TABLES, };