const { Pool } = require('pg');
require('dotenv').config();

const pool = new Pool({
	host: process.env.DB_HOST || 'localhost',
	port: process.env.DB_PORT || 5432,
	database: process.env.DB_NAME || 'bekind',
	user: process.env.DB_USER || 'postgres',
	password: process.env.DB_PASSWORD,
});

async function cleanUsers() {
	const client = await pool.connect();
	try {
		await client.query('BEGIN');

		console.log('🧹 Cleaning users...\n');

		// Delete all user_auth records first (due to foreign key)
		const deletedAuth = await client.query('DELETE FROM user_auth');
		console.log(`✅ Deleted ${deletedAuth.rowCount} user_auth records`);

		// Delete all user_roles
		const deletedUserRoles = await client.query('DELETE FROM user_roles');
		console.log(`✅ Deleted ${deletedUserRoles.rowCount} user_roles records`);

		// Delete all users
		const deletedUsers = await client.query('DELETE FROM users');
		console.log(`✅ Deleted ${deletedUsers.rowCount} users`);

		await client.query('COMMIT');
		console.log('\n✅ Users cleaned successfully');
	} catch (error) {
		await client.query('ROLLBACK');
		console.error('❌ Cleaning failed:', error.message);
		throw error;
	} finally {
		client.release();
		await pool.end();
	}
}

cleanUsers().catch((err) => {
	console.error(err);
	process.exit(1);
});
