import pg from 'pg';

const DATABASE_URL = 'postgresql://edumanager:EduManager2026!Seguro@150.230.87.131:5432/edumanager';
const pool = new pg.Pool({ connectionString: DATABASE_URL });

async function restore() {
  try {
    console.log('--- RESTORING & APPROVING EVILLA JUSTIFICATION ---');
    
    // 1. Update SQL table
    console.log('1. Updating "frequencias" table on VPS (Accepted = TRUE)...');
    const justPayload = JSON.stringify({
      motivo: 'tive que levar a minha cadela para outra cidade para o veterinário, não teria como “faltar”',
      arquivo: null
    });

    const sqlRes = await pool.query(
      `UPDATE frequencias 
       SET tipo = 'absence', 
           justificativa = $1, 
           justificativa_aceita = true, 
           aula_id = 'c73336be-c437-4808-ab40-4e8d7439388b' 
       WHERE id = 'auto-abs-1780168194386-jaewp'`,
      [justPayload]
    );
    console.log(`Updated in SQL: ${sqlRes.rowCount} row(s)`);

    // 2. Update JSON blob
    console.log('2. Updating school_data JSON blob on VPS (Accepted = TRUE)...');
    const { rows } = await pool.query('SELECT data FROM school_data WHERE id = 1');
    if (rows.length === 0) {
      throw new Error('school_data table is empty or missing id=1');
    }
    const schoolData = rows[0].data;
    if (!schoolData.attendance) {
      schoolData.attendance = [];
    }

    let updatedCount = 0;
    schoolData.attendance = schoolData.attendance.map(record => {
      if (record.id === 'auto-abs-1780168194386-jaewp' || 
         (record.studentId === '311709fb-68ab-4168-8684-887b5ec2d731' && record.date.startsWith('2026-05-30'))) {
        updatedCount++;
        return {
          ...record,
          type: 'absence',
          justification: justPayload,
          justificationAccepted: true,
          lessonId: 'c73336be-c437-4808-ab40-4e8d7439388b'
        };
      }
      return record;
    });

    if (updatedCount === 0) {
      console.log('Record not found in JSON array. Creating new one...');
      schoolData.attendance.push({
        id: 'auto-abs-1780168194386-jaewp',
        date: '2026-05-30T14:00:00',
        type: 'absence',
        photo: null,
        classId: '9f47fde6-0637-4f54-a3c2-9fd9b68b2022',
        lessonId: 'c73336be-c437-4808-ab40-4e8d7439388b',
        verified: false,
        studentId: '311709fb-68ab-4168-8684-887b5ec2d731',
        justification: justPayload,
        justificationAccepted: true,
        createdAt: '2026-05-30T19:47:33.723Z'
      });
      updatedCount = 1;
    }

    const saveRes = await pool.query(
      'UPDATE school_data SET data = $1, updated_at = NOW() WHERE id = 1',
      [JSON.stringify(schoolData)]
    );
    console.log(`Updated in JSON: ${updatedCount} record(s). DB Update: ${saveRes.rowCount}`);

    console.log('--- RESTORATION & APPROVAL COMPLETED SUCCESSFULLY ---');
  } catch (err) {
    console.error('ERROR during restoration:', err.message);
  } finally {
    await pool.end();
  }
}

restore();
