import { PrismaClient } from '@prisma/client';
import { Pool } from 'pg';
import { PrismaPg } from '@prisma/adapter-pg';
import { uploadToOpeninary } from '../lib/openinary';
import fs from 'fs';
import path from 'path';
import 'dotenv/config';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });

async function main() {
    console.log("Uploading default product image to Openinary...");
    const localPath = path.join(process.cwd(), 'public', 'default-product.png');
    const buffer = fs.readFileSync(localPath);
    const file = new File([buffer], 'default-product.png', { type: 'image/png' });

    let defaultPath = "";
    try {
        const result = await uploadToOpeninary(file, "kiteqr");
        defaultPath = result.path;
        console.log(`[SUCCESS] Default image uploaded to: ${defaultPath}`);
    } catch (error) {
        console.error("Failed to upload default image:", error);
        return;
    }

    console.log("Updating products with missing or old images...");
    const products = await prisma.products.findMany();
    
    let updatedCount = 0;
    for (const product of products) {
        // If image_url is empty, null, or doesn't start with kiteqr/ (meaning it wasn't migrated successfully)
        if (!product.image_url || !product.image_url.startsWith('kiteqr/')) {
            await prisma.products.update({
                where: { id: product.id },
                data: { image_url: defaultPath }
            });
            updatedCount++;
            console.log(`Updated product ${product.id} (${product.name}) with mock image.`);
        }
    }

    console.log(`Done. ${updatedCount} products updated with the mock image.`);
}

main()
    .catch(console.error)
    .finally(() => prisma.$disconnect());
