"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("dotenv/config");
const db_1 = require("../db");
const schema_1 = require("../db/schema");
const drizzle_orm_1 = require("drizzle-orm");
async function fixActivities() {
    console.log("Starting to fix status_change activities...");
    // 1. Fetch all status_change activities
    const statusChanges = await db_1.db.select().from(schema_1.activities).where((0, drizzle_orm_1.eq)(schema_1.activities.type, 'status_change'));
    console.log(`Found ${statusChanges.length} status_change activities.`);
    let fixedCount = 0;
    for (const activity of statusChanges) {
        if (!activity.metadata || Object.keys(activity.metadata).length === 0) {
            // Try to extract status from description
            // Example: "Changed status from 'New' to 'Attempted Contact'"
            const match = activity.description?.match(/to '([^']+)'/);
            if (match && match[1]) {
                const newStatus = match[1];
                console.log(`Fixing activity ${activity.id}: Setting newStatus to '${newStatus}'`);
                await db_1.db.update(schema_1.activities)
                    .set({ metadata: { newStatus } })
                    .where((0, drizzle_orm_1.eq)(schema_1.activities.id, activity.id));
                fixedCount++;
            }
            else {
                // Secondary check for "Marked as Booked with profit..."
                const match2 = activity.description?.match(/Marked as ([^ ]+)/);
                if (match2 && match2[1]) {
                    const newStatus = match2[1];
                    console.log(`Fixing activity ${activity.id}: Setting newStatus to '${newStatus}' from manual log`);
                    await db_1.db.update(schema_1.activities)
                        .set({ metadata: { newStatus } })
                        .where((0, drizzle_orm_1.eq)(schema_1.activities.id, activity.id));
                    fixedCount++;
                }
            }
        }
    }
    // 2. Also handle lead_created type
    const leadCreated = await db_1.db.select().from(schema_1.activities).where((0, drizzle_orm_1.eq)(schema_1.activities.type, 'lead_created'));
    console.log(`Found ${leadCreated.length} lead_created activities.`);
    for (const activity of leadCreated) {
        if (!activity.metadata || Object.keys(activity.metadata).length === 0) {
            // Usually starts as 'New'
            console.log(`Fixing activity ${activity.id}: Setting newStatus to 'New' for lead_created`);
            await db_1.db.update(schema_1.activities)
                .set({ metadata: { newStatus: 'New' } })
                .where((0, drizzle_orm_1.eq)(schema_1.activities.id, activity.id));
            fixedCount++;
        }
    }
    console.log(`Finished. Fixed ${fixedCount} activities.`);
    process.exit(0);
}
fixActivities().catch(err => {
    console.error(err);
    process.exit(1);
});
