const STUDENT_STATUSES = ['active', 'paused', 'left']; function normalizeStudentStatus(value) { if (value === undefined) return undefined; const status = String(value ?? '').trim(); return STUDENT_STATUSES.includes(status) ? status : null; } async function ensureStudentPhotosTable(pool) { await pool.query(`CREATE TABLE IF NOT EXISTS student_photos ( id SERIAL PRIMARY KEY, student_id INT NOT NULL REFERENCES students(id) ON DELETE CASCADE, photo_path VARCHAR(255) NOT NULL, created_at TIMESTAMPTZ DEFAULT now() )`); await pool.query('CREATE INDEX IF NOT EXISTS idx_student_photos_student_id ON student_photos(student_id)'); } function createStudentProfileAccess(pool, groupBelongsToBranches) { return async function studentProfileAccess(user, id) { const { rows } = await pool.query( 'SELECT id, name, group_id, photo_path, profile FROM students WHERE id = $1 AND deleted_at IS NULL', [id] ); if (!rows.length) return { found: false }; const gid = rows[0].group_id; if (user.role !== 'admin' && gid && !(await groupBelongsToBranches(user, gid))) { return { found: false, forbidden: true }; } return { found: true, student: rows[0] }; }; } async function ensureStudentsTable(pool) { await pool.query(`ALTER TABLE students ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'active'`); const { rows } = await pool.query( `SELECT 1 FROM pg_constraint WHERE conname = 'students_status_check' AND conrelid = 'students'::regclass` ); if (!rows.length) { await pool.query( `ALTER TABLE students ADD CONSTRAINT students_status_check CHECK (status IN ('active','paused','left')) NOT VALID` ); } await pool.query(`ALTER TABLE students VALIDATE CONSTRAINT students_status_check`); } module.exports = { STUDENT_STATUSES, normalizeStudentStatus, ensureStudentsTable, ensureStudentPhotosTable, createStudentProfileAccess };