import * as dotenv from 'dotenv'
dotenv.config({ path: '.env' })
dotenv.config({ path: '.env.local' })

async function main() {
  const { default: prisma } = await import('../lib/prisma')
  const { uploadToOpeninary } = await import('../lib/openinary')
  const { optimizedImage } = await import('../lib/openinary-url')

  console.log("Starting image migration from Cloudinary to Openinary...");

  // FIX PREVIOUSLY CORRUPTED URLS
  const corruptedProducts = await prisma.products.findMany({
    where: { image_url: { startsWith: 'undefined/t/' } }
  });
  if (corruptedProducts.length > 0) {
    console.log(`Fixing ${corruptedProducts.length} corrupted products...`);
    for (const prod of corruptedProducts) {
      const fixedUrl = prod.image_url?.replace('undefined', process.env.NEXT_PUBLIC_OPENINARY_URL || 'https://media.ayris.tech');
      if (fixedUrl) {
        await prisma.products.update({ where: { id: prod.id }, data: { image_url: fixedUrl } });
      }
    }
  }

  const corruptedLogo = await prisma.settings.findUnique({ where: { key: 'logo_url' } });
  if (corruptedLogo?.value?.startsWith('undefined/t/')) {
    const fixedUrl = corruptedLogo.value.replace('undefined', process.env.NEXT_PUBLIC_OPENINARY_URL || 'https://media.ayris.tech');
    await prisma.settings.update({ where: { key: 'logo_url' }, data: { value: fixedUrl } });
  }

  async function downloadAndUpload(url: string, fileName: string): Promise<string> {
    console.log(`Downloading ${url}...`);
    const response = await fetch(url);
    if (!response.ok) throw new Error(`Failed to download ${url}`);
    
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);
    
    const blob = new Blob([buffer], { type: response.headers.get('content-type') || 'image/jpeg' });
    const file = new File([blob], fileName, { type: blob.type });

    console.log(`Uploading ${fileName} to Openinary...`);
    const result = await uploadToOpeninary(file, 'moyqr');
    
    return optimizedImage(result.path, 'w_800,h_800,c_limit,q_auto,f_auto');
  }

  // 1. Settings Logo
  const logoSetting = await prisma.settings.findUnique({
    where: { key: 'logo_url' }
  });

  if (logoSetting?.value && logoSetting.value.includes('res.cloudinary.com')) {
    try {
      const newUrl = await downloadAndUpload(logoSetting.value, 'logo.png');
      await prisma.settings.update({
        where: { key: 'logo_url' },
        data: { value: newUrl }
      });
      console.log(`Logo updated successfully: ${newUrl}`);
    } catch (e) {
      console.error("Failed to migrate logo:", e);
    }
  }

  // 2. Products
  const products = await prisma.products.findMany({
    where: {
      image_url: {
        contains: 'res.cloudinary.com'
      }
    }
  });

  console.log(`Found ${products.length} products with Cloudinary images.`);

  for (const product of products) {
    if (!product.image_url) continue;
    try {
      const ext = product.image_url.split('.').pop() || 'jpg';
      const fileName = `product-${product.id}.${ext}`;
      const newUrl = await downloadAndUpload(product.image_url, fileName);
      
      await prisma.products.update({
        where: { id: product.id },
        data: { image_url: newUrl }
      });
      console.log(`Product ${product.id} updated successfully: ${newUrl}`);
    } catch (e) {
      console.error(`Failed to migrate product ${product.id}:`, e);
    }
  }

  console.log("Migration finished.");
}

main()
  .catch(e => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
    try {
      const { default: prisma } = await import('../lib/prisma')
      await prisma.$disconnect()
    } catch (e) {
      // ignore
    }
  })
