import { Injectable, Logger } from '@nestjs/common';
import { SocketGuardsGateway } from 'src/shared/socket-guards/services/socket-guards.gateway';
import { IFullUser } from '../users/users.interface';

export type DebugEventType =
	| 'http:request_start'
	| 'http:request_end'
	| 'chat:request_received'
	| 'chat:llm_dispatch'
	| 'chat:llm_first_chunk'
	| 'chat:filter_check_start'
	| 'chat:filter_check_end'
	| 'chat:filter_blocked'
	| 'chat:stream_word'
	| 'chat:db_save'
	| 'chat:complete'
	| 'image:request_received'
	| 'image:provider_dispatch'
	| 'image:provider_response'
	| 'image:db_save'
	| 'image:socket_emit'
	| 'image:complete'
	| 'image:blocked'
	| 'image:final_prompt'
	| 'image:provider_response'
	| 'chat:cost'
	| 'image:cost'
	| 'audio:cost'
	| 'error';

export interface IDebugEvent {
	id?: string;
	type: DebugEventType;
	stage?: string;
	ms?: number;            // duration of this stage (if applicable)
	data?: any;             // small structured payload — keep light
	contextId?: string;     // groups events for one request (e.g. conversationId or imageId)
	at?: number;            // server timestamp
}

@Injectable()
export class DebugEventsService {
	private readonly logger = new Logger(DebugEventsService.name);

	private get whitelist(): string[] {
		const list = (process.env.DEBUG_USERS_EMAILS || '').toLowerCase();
		return list ? list.split(',').map(s => s.trim()).filter(Boolean) : [];
	}

	constructor(private readonly socketGateway: SocketGuardsGateway) {}

	isDebugUser(user?: IFullUser | null): boolean {
		if (!user?.email) return false;
		return this.whitelist.includes(user.email.toLowerCase());
	}

	async emit(user: IFullUser | null | undefined, event: IDebugEvent): Promise<void> {
		try {
			if (!user || !this.isDebugUser(user)) return;
			const payload: IDebugEvent = {
				...event,
				at: Date.now(),
			};
			await this.socketGateway.sendToUser('debug:event', user._id.toString(), payload);
		} catch (e) {
			this.logger.warn(`emit failed: ${(e as Error).message}`);
		}
	}
}
