import { GatewayAdapter } from './adapter-interface';
import { AdapterReceiveResult, AdapterSendResult, AdapterValidateResult } from './adapter-types';

export abstract class AdapterBase implements GatewayAdapter {
	protected configuration: Record<string, unknown> = {};
	protected secretsRef?: string;

	async initialize(config: Record<string, unknown>, secretsRef?: string): Promise<void> {
		this.configuration = { ...config };
		this.secretsRef = secretsRef;
	}

	async health(): Promise<{ status: 'UP' | 'DOWN'; details?: Record<string, unknown> }> {
		return { status: 'UP' };
	}

	async capabilities(): Promise<string[]> {
		return [];
	}

	abstract validate(canonicalInstruction: Record<string, unknown>): Promise<AdapterValidateResult>;
	abstract send(outboxRecord: {
		txnId: string;
		payloadHash: string;
		envelope: unknown;
	}): Promise<AdapterSendResult>;
	abstract receive(rawRailMessage: unknown): Promise<AdapterReceiveResult>;

	mapStatus(rail: { code: string; description?: string; source?: string }): {
		status: string;
		railStatus: { code: string; description?: string; source?: string };
	} {
		return { status: 'IN_PROGRESS', railStatus: rail };
	}

	finalityHints(railStatus: { code: string }): { hint?: 'PROVISIONAL' | 'FINAL' | 'IRREVERSIBLE' } {
		// Default: unknown
		if (railStatus.code.toUpperCase().includes('FINAL')) return { hint: 'FINAL' };
		return {};
	}

	errorMap(railError: { code: string; message?: string }): {
		errorCode: string;
		retryClass: 'RETRYABLE' | 'NON_RETRYABLE' | 'MANUAL_REVIEW';
	} {
		const code = railError.code || 'UNKNOWN';
		const retryClass = code.startsWith('T') ? 'RETRYABLE' : 'MANUAL_REVIEW';
		return { errorCode: code, retryClass };
	}
}

