import { Req, Res } from '#interfaces/IApi';
import { NextFunction } from 'express';
import { GenericError } from '#interfaces/error/generic';
import Config from '#config';

/**
 * Webhook authentication middleware
 * Verifies X-Webhook-Token or Authorization Bearer token
 */
export async function verifyWebhookToken(req: Req, res: Res, next: NextFunction): Promise<void> {
	try {
		// Get webhook token from environment
		const webhookToken = Config.webhook?.token;

		if (!webhookToken) {
			const error = new GenericError('INTERNAL_SERVER_ERROR');
			error.message = 'Webhook token not configured';
			return res.error(error);
		}

		// Try to get token from X-Webhook-Token header first
		let token: string | undefined = req.header('X-Webhook-Token');

		// Fallback to Authorization Bearer header
		if (!token) {
			const authHeader = req.header('Authorization');
			if (authHeader) {
				const [bearer, bearerToken] = authHeader.split(' ');
				if (bearer === 'Bearer' && bearerToken) {
					token = bearerToken;
				}
			}
		}

		if (!token) {
			const error = new GenericError('UNAUTHORIZED');
			error.message = 'Missing webhook token';
			return res.error(error);
		}

		// Verify token
		if (token !== webhookToken) {
			const error = new GenericError('UNAUTHORIZED');
			error.message = 'Invalid webhook token';
			return res.error(error);
		}

		next();
	} catch (err) {
		if (err instanceof GenericError) {
			return res.error(err);
		}
		return res.error(new GenericError('INTERNAL_SERVER_ERROR'));
	}
}
