/**
 * Script: Reset password for a specific user
 * Usage: npx tsx scripts/reset-password.ts <email> <newPassword>
 *
 * Example: npx tsx scripts/reset-password.ts onosocobo124@gmail.com "VietPro@2026"
 */
import crypto from 'crypto';
import { PasswordService } from '../src/services/auth/passwordService';
import sequelize from '../src/services/database/sequelize/sequelizeService';
import { User } from '../src/models/User';
import { UserAuth } from '../src/models/UserAuth';

async function main() {
	const [,, rawEmail, ...rawPasswordParts] = process.argv;
	const newPassword = rawPasswordParts.join(' ');

	if (!rawEmail || !newPassword) {
		// eslint-disable-next-line no-console
		console.error('Usage: npx tsx scripts/reset-password.ts <email> <newPassword>');
		process.exit(1);
	}

	// eslint-disable-next-line no-console
	console.log(`[ResetPassword] Connecting to DB...`);
	await sequelize.authenticate();
	// eslint-disable-next-line no-console
	console.log(`[ResetPassword] Connected.`);

	// Step 1: Find user by email
	const userRecord = await User.findOne({ where: { email: rawEmail } as any });
	if (!userRecord) {
		// eslint-disable-next-line no-console
		console.error(`[ResetPassword] User not found: ${rawEmail}`);
		await sequelize.close();
		process.exit(1);
	}
	// eslint-disable-next-line no-console
	console.log(`[ResetPassword] Found user: ${userRecord.id} (${rawEmail})`);

	// Step 2: Find or create user_auth by user UUID
	let targetRecord = await UserAuth.findOne({ where: { user_id: userRecord.id } as any });

	if (!targetRecord) {
		// eslint-disable-next-line no-console
		console.warn(`[ResetPassword] user_auth record not found, creating...`);
		const newHash = await PasswordService.hashPassword(newPassword);
		await UserAuth.create({
			id: crypto.randomUUID(),
			user_id: userRecord.id,
			password_hash: newHash,
		} as any);
		// eslint-disable-next-line no-console
		console.log(`[ResetPassword] Created user_auth + set new password hash.`);
	} else {
		const newHash = await PasswordService.hashPassword(newPassword);
		await targetRecord.update({ password_hash: newHash } as any);
		// eslint-disable-next-line no-console
		console.log(`[ResetPassword] Updated password hash for ${rawEmail}.`);
	}

	await sequelize.close();
	// eslint-disable-next-line no-console
	console.log(`[ResetPassword] Done.`);
}

main().catch((err) => {
	// eslint-disable-next-line no-console
	console.error('[ResetPassword] Error:', err);
	process.exit(1);
});
