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("Starting migration...");
    const products = await prisma.products.findMany({
        where: {
            image_url: { not: null }
        }
    });

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

    for (const product of products) {
        if (!product.image_url) continue;

        if (product.image_url.startsWith('kiteqr/')) {
            console.log(`[SKIP] Already migrated ${product.id}`);
            continue;
        }

        // Extract filename from image_url (e.g. admin/uploads/products/xxx.jpg or similar)
        const filename = path.basename(product.image_url);
        if (!filename) continue;

        const localPath = path.join(process.cwd(), 'products', filename);

        if (!fs.existsSync(localPath)) {
            console.log(`[SKIP] Local file not found for product ${product.id} (${product.name}): ${localPath}`);
            continue;
        }

        try {
            console.log(`[UPLOAD] Uploading ${filename} for product ${product.id}...`);
            const buffer = fs.readFileSync(localPath);
            
            const ext = path.extname(filename).toLowerCase();
            let mime = 'image/jpeg';
            if (ext === '.png') mime = 'image/png';
            if (ext === '.webp') mime = 'image/webp';
            if (ext === '.gif') mime = 'image/gif';
            
            const file = new File([buffer], filename, { type: mime });

            const result = await uploadToOpeninary(file, "kiteqr");
            
            console.log(`[SUCCESS] Uploaded to: ${result.path}`);

            // Update database
            await prisma.products.update({
                where: { id: product.id },
                data: { image_url: result.path } // Using path as requested/required by loader
            });

        } catch (error) {
            console.error(`[ERROR] Failed to upload/update product ${product.id}:`, error);
        }
    }

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

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