import { createClient } from '@libsql/client';
import { drizzle } from 'drizzle-orm/libsql';
import { eq } from 'drizzle-orm';
import { user } from '../src/lib/server/db/auth.schema';

const DATABASE_URL = process.env.DATABASE_URL || 'file:local.db';

function getErrorMessage(error: unknown): string {
	return error instanceof Error ? error.message : String(error);
}

async function promoteAdmin(): Promise<void> {
	const email = process.argv[2]?.trim();

	if (!email) {
		console.error('❌ Missing email argument');
		console.error('Usage: npm run user:promote-admin -- <email>');
		process.exit(1);
	}

	const client = createClient({ url: DATABASE_URL });
	const db = drizzle(client);

	try {
		const existingUsers = await db.select().from(user).where(eq(user.email, email)).limit(1);
		const targetUser = existingUsers[0];

		if (!targetUser) {
			console.error(`❌ User not found for email: ${email}`);
			process.exit(1);
		}

		if (targetUser.isAdmin) {
			console.log(`ℹ️ User is already admin: ${targetUser.email}`);
			return;
		}

		await db
			.update(user)
			.set({ isAdmin: true })
			.where(eq(user.id, targetUser.id));

		console.log(`✅ Admin granted to: ${targetUser.email}`);
	} catch (error) {
		console.error(`❌ Failed to promote admin: ${getErrorMessage(error)}`);
		process.exit(1);
	} finally {
		client.close();
	}
}

promoteAdmin().catch((error) => {
	console.error(getErrorMessage(error));
	process.exit(1);
});
