const PocketBase = require('pocketbase').default
const sharp = require('sharp')

// Initialize the PocketBase client
const pb = new PocketBase('http://127.0.0.1:8090')

async function main () {
  try {
    // Authenticate as an admin
    await pb.admins.authWithPassword('karkinge@gmail.com', 'XXXXXXX') // Replace with your admin credentials

    // Parse JSON file with categories
    const filesPath = '../gyoza/storage/'

    // Get history collection
    const historyCollection = await pb.collection('history').getFullList({ filter: 'image_file = null' })
    for (let hist of historyCollection) {
      if (hist.image) {
        console.log(hist)
        let fullPath = filesPath + hist.image
        // Compress the image with a 80% quality
        const compressedImage = await sharp(fullPath)
          .resize({ width: 2000, height: 2000, fit: 'inside' })
          .jpeg({ quality: 80 })
          .toBuffer()

        // Create a JS file object from the file's content
        const file = new File([compressedImage], hist.image)
        await pb.collection('history').update(hist.id, { image_file: file })
      }
    }
  } catch (error) {
    console.error('Error:', error)
  }
}

main()
