import dotenv from 'dotenv';
import { getSample } from './controllers/samples.js';
import query, { transaction } from './server-utils/query.js';

dotenv.config();

const DESIRED_COMPRESSED_EXTENSIONS = ['ogg'];

const cleanSampleRow = async (row) => {
  const {
    id: sampleId,
    s3_key: s3Key,
    compressed_s3_key: compressedS3Key,
    length_in_ms: lengthInMs,
    has_waveform: hasWaveform,
  } = row;
  console.log(`Cleaning sample: ${JSON.stringify(row)}`);
  let needsUpdate = lengthInMs === null || !hasWaveform;
  if (
    s3Key !== null &&
    compressedS3Key !== null &&
    !DESIRED_COMPRESSED_EXTENSIONS.includes(compressedS3Key.split('.').pop())
  ) {
    console.log(`Recompressing to opus: ${sampleId} - ${s3Key}`);
    await query('UPDATE samples SET compressed_s3_key = NULL WHERE id = $1', [sampleId]);
    needsUpdate = true;
  }
  if (needsUpdate) {
    await getSample(
      { id: sampleId, bypassPermissionCheck: true },
      { returnLength: true, ensureWaveform: true, returnCompressed: true }
    );
  }
};

await transaction(async (transactionQuery) => {
  await transactionQuery('SET TRANSACTION ISOLATION LEVEL READ COMMITTED, READ ONLY', []);

  const pageSize = 100;
  let offset = 0;
  while (true) {
    const samplesQuery = await transactionQuery(
      `
      SELECT id,
             s3_key,
             compressed_s3_key,
             length_in_ms,
             waveform_svg IS NOT NULL has_waveform
       FROM samples ORDER BY id ASC OFFSET $1 LIMIT $2
    `,
      [offset, pageSize]
    );
    if (samplesQuery.rows.length === 0) {
      break;
    }
    for (let row of samplesQuery.rows) {
      await cleanSampleRow(row);
    }
    offset += samplesQuery.rows.length;
  }
});
