import { PasswordResetTokenProvider } from '#providers/PasswordResetTokenProvider';
import LoggingService from '#services/file-system/logService';
import { Op } from 'sequelize';

/**
 * Password reset job for cleaning expired reset codes
 * Removes expired password reset codes that haven't been used
 */

const logger = new LoggingService();

export class PasswordResetJob {
	static async run(): Promise<void> {
		try {
			logger.logInfoAsync('PasswordResetJob', new Error('Starting password reset cleanup job'), null);

			// Clean up expired unused reset codes
			const deletedCount = await PasswordResetJob.cleanupExpiredCodes();

			logger.logInfoAsync('PasswordResetJob', new Error(`Cleaned up ${deletedCount} expired reset codes`), null);
		} catch (error) {
			logger.logErrorAsync('PasswordResetJob', error as Error, null);
			throw error;
		}
	}

	/**
	 * Remove expired password reset codes
	 */
	private static async cleanupExpiredCodes(): Promise<number> {
		const provider = PasswordResetTokenProvider.getInstance();
		const now = new Date();

		// Delete expired codes that haven't been used
		const result = await provider.bulkDelete({
			expires_at: {
				[Op.lt]: now,
			},
			used_at: null,
		});

		return result;
	}

	/**
	 * Remove used reset codes older than 24 hours (for security)
	 */
	static async cleanupUsedCodes(): Promise<number> {
		const provider = PasswordResetTokenProvider.getInstance();
		const oneDayAgo = new Date();
		oneDayAgo.setHours(oneDayAgo.getHours() - 24);

		const result = await provider.bulkDelete({
			used_at: {
				[Op.lt]: oneDayAgo,
			},
		});

		logger.logInfoAsync('PasswordResetJob', new Error(`Cleaned up ${result} used reset codes older than 24h`), null);

		return result;
	}
}
