
import 'dotenv/config';
import { getDatabase } from '../src/lib/database';
import { clerkClient } from '@clerk/nextjs/server';

async function syncAllUsers() {
    console.log('Starting full user sync...');
    const db = await getDatabase();

    // Fetch all users from Clerk
    // Note: pagination might be needed for large user bases, but for prototype this is fine.
    const client = await clerkClient();
    const response = await client.users.getUserList({ limit: 100 });
    const clerkUsers = response.data;

    console.log(`Found ${clerkUsers.length} users in Clerk.`);

    for (const clerkUser of clerkUsers) {
        const userId = clerkUser.id;
        const email = clerkUser.emailAddresses[0]?.emailAddress;

        if (!email) {
            console.warn(`User ${userId} has no email, skipping.`);
            continue;
        }

        const existingUser = await db.getUserById(userId);
        if (existingUser) {
            console.log(`User ${email} (${userId}) already exists.`);
            // Optional: Update details if needed
            continue;
        }

        // Check by email to handle ID mismatches (e.g. from seeding)
        const existingByEmail = await db.getUserByEmail(email);
        if (existingByEmail) {
            console.log(`User ${email} found with old ID ${existingByEmail.id}. Migrating to ${userId}...`);
            await db.migrateUserId(existingByEmail.id, userId);
            continue;
        }

        console.log(`Creating new user ${email} (${userId})...`);
        await db.createUser({
            id: userId,
            email,
            firstName: clerkUser.firstName || '',
            lastName: clerkUser.lastName || '',
            password: '', // Managed by Clerk
            phone: clerkUser.phoneNumbers[0]?.phoneNumber || undefined,
            role: (clerkUser.publicMetadata.role as 'admin' | 'client' | 'superAdmin') || 'client'
        });
    }

    console.log('Sync complete.');
}

syncAllUsers().catch(console.error);
