const { createClient } = require('@supabase/supabase-js');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '../.env') });

const supabase = createClient(
    process.env.SUPABASE_URL,
    process.env.SUPABASE_SERVICE_ROLE_KEY
);

async function cleanup() {
    const prefix = 'd8ac';

    // 1. Find the full user_id
    const { data: logData, error: logError } = await supabase
        .from('logs')
        .select('user_id')
        .ilike('user_id', `${prefix}%`)
        .limit(1);

    if (logError) {
        console.error('Error searching logs:', logError.message);
        return;
    }

    const fullUserId = logData?.[0]?.user_id;

    if (!fullUserId) {
        console.log(`No device found starting with ${prefix}`);
        return;
    }

    console.log(`Found full device ID: ${fullUserId}`);

    // 2. Delete logs
    console.log('Cleaning up logs...');
    const { count: logCount, error: logDelError } = await supabase
        .from('logs')
        .delete({ count: 'exact' })
        .eq('user_id', fullUserId);

    if (logDelError) {
        console.error('Error deleting logs:', logDelError.message);
    } else {
        console.log(`Successfully deleted ${logCount} log entries.`);
    }

    // 3. Delete messages
    console.log('Cleaning up message history...');
    const { count: msgCount, error: msgDelError } = await supabase
        .from('messages')
        .delete({ count: 'exact' })
        .eq('user_id', fullUserId);

    if (msgDelError) {
        console.error('Error deleting messages:', msgDelError.message);
    } else {
        console.log(`Successfully deleted ${msgCount} message entries.`);
    }

    // 4. Delete sessions (if any)
    console.log('Cleaning up sessions...');
    const { count: sessCount, error: sessDelError } = await supabase
        .from('sessions')
        .delete({ count: 'exact' })
        .eq('user_id', fullUserId);

    if (sessDelError) {
        console.error('Error deleting sessions:', sessDelError.message);
    } else {
        console.log(`Successfully deleted ${sessCount} session entries.`);
    }

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

cleanup();
