import { Req, Res } from '#interfaces/IApi';
import { NextFunction } from 'express';

type Platform = 'web' | 'mobile' | 'zalo_miniapp' | 'internal';

declare module 'express' {
	interface Request {
		platform?: Platform;
		deviceId?: string | undefined;
		deviceName?: string | undefined;
	}
}

const VALID_PLATFORMS: Platform[] = ['web', 'mobile', 'zalo_miniapp', 'internal'];

/**
 * Extract platform from X-Platform header
 * FE MUST explicitly send X-Platform header
 * User-Agent detection is ONLY fallback for legacy clients
 */
export function detectPlatform(req: Req, res: Res, next: NextFunction): void {
	let platform: Platform = 'web'; // Conservative default

	// 1. Primary: X-Platform header (REQUIRED for explicit contracts)
	const headerPlatform = req.header('X-Platform') as string;
	if (headerPlatform && VALID_PLATFORMS.includes(headerPlatform as Platform)) {
		platform = headerPlatform as Platform;
	}
	// 2. Fallback: User-Agent (for backward compatibility only)
	else {
		const userAgent = req.header('User-Agent') || '';
		if (userAgent.includes('Zalo') || userAgent.includes('MiniApp')) {
			platform = 'zalo_miniapp';
		}
		// NOTE: Removed Mobile/Android/iOS detection - too unreliable
		// Mobile clients MUST send X-Platform: mobile
	}

	req.platform = platform;

	// Extract device info from headers only (no body fallback)
	req.deviceId = req.header('X-Device-Id') || undefined;
	req.deviceName = req.header('X-Device-Name') || undefined;

	next();
}

/**
 * Require explicit platform header
 * Use this middleware when you want to enforce explicit platform declaration
 */
export function requireExplicitPlatform(req: Req, res: Res, next: NextFunction): void {
	const headerPlatform = req.header('X-Platform') as string;

	if (!headerPlatform || !VALID_PLATFORMS.includes(headerPlatform as Platform)) {
		res.status(400).json({
			success: false,
			error_code: 'MISSING_PLATFORM_HEADER',
			message: {
				vi: 'Thiếu header X-Platform. Các giá trị hợp lệ: web, mobile, zalo_miniapp, internal',
				en: 'Missing X-Platform header. Valid values: web, mobile, zalo_miniapp, internal',
			},
		});
		return;
	}

	next();
}

/**
 * Require specific platform
 */
export function requirePlatform(requiredPlatform: Platform) {
	return (req: Req, res: Res, next: NextFunction): void => {
		if (req.platform !== requiredPlatform) {
			res.status(400).json({
				success: false,
				error_code: 'INVALID_PLATFORM',
				message: {
					vi: `Endpoint này yêu cầu platform ${requiredPlatform}`,
					en: `This endpoint requires ${requiredPlatform} platform`,
				},
			});
			return;
		}
		next();
	};
}

export { Platform };
