import { Reel } from "../api/reels/models"

function isCompressed(url: string) {
  const filename = url.split('.').at(-2)
  return !!filename?.endsWith('-compressed')
}

function uncompress(url: string) {
  const split = url.split('.')
  let filename = split.at(-2)
  if(filename?.endsWith('-compressed')) {
    filename = filename.substring(0, filename.length - '-compressed'.length)
  }
  let newSplit = [...split.slice(0, split.length - 2), filename, split.at(-1)]
  return newSplit.join('.')
}

async function execute() {
  const reels = await Reel.find()
  console.log('')
  for(let i = 0; i < reels.length; i++) {
    const reel = reels[i]
    let flag = false
    if(reel.video && isCompressed(reel.video)) {
      reel.video = uncompress(reel.video)
      flag = true
    }
    if(reel.dynamic) {
      for(const d of reel.dynamic) {
        if(isCompressed(d.video)) {
          d.video = uncompress(d.video)
          flag = true
        }
      }
    }
    if(flag) {
      console.log('\rreel', reel._id.toString(), 'reverting')
      await reel.save()
    }
    await new Promise((r) => setTimeout(r, 100))
    process.stdout.write(`\r${i+1}/${reels.length}`)
  }
  console.log('\r✅ Done            ')
}

const scriptRevertCompressedReels = {
  isCompressed,
  uncompress,
  execute
}

export default scriptRevertCompressedReels