import { getContainer } from '@bytelyst/cosmos';
import { randomUUID } from 'node:crypto';
import { config } from '../config/index.js';

export const ORDER_CONTAINER = 'trade_orders';
export const TRADE_HISTORY_CONTAINER = 'trade_history';
export const MANUAL_ENTRY_CONTAINER = 'manual_entries';
export const RECONCILIATION_AUDIT_CONTAINER = 'reconciliation_backfill_audit';

export interface TradingRecordDocument {
    id: string;
    productId: string;
    type: string;
    created_at: string;
    updated_at: string;
}

export function isCosmosConfigured(): boolean {
    return Boolean(config.COSMOS_ENDPOINT && config.COSMOS_KEY && config.COSMOS_DATABASE);
}

export function requireCosmosConfigured(): void {
    if (!isCosmosConfigured()) {
        throw new Error('Cosmos DB is not configured for trading record persistence');
    }
}

export function nowIso(): string {
    return new Date().toISOString();
}

export function clampNumber(value: unknown, fallback: number = 0): number {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : fallback;
}

export function toOptionalString(value: unknown): string | undefined {
    const text = String(value || '').trim();
    return text || undefined;
}

export function toOptionalNumber(value: unknown): number | undefined {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : undefined;
}

export function buildDocId(...parts: Array<unknown>): string {
    const normalized = parts
        .map((part) => String(part || '').trim())
        .filter(Boolean)
        .join('::');
    return normalized || randomUUID();
}

export async function queryDocuments<T>(containerName: string, query: string, parameters: Array<{ name: string; value: unknown }>): Promise<T[]> {
    requireCosmosConfigured();
    const container = getContainer(containerName);
    const { resources } = await container.items.query<T>({ query, parameters: parameters as any }).fetchAll();
    return resources;
}

export async function upsertDocument<T extends TradingRecordDocument>(containerName: string, document: T): Promise<T> {
    requireCosmosConfigured();
    const container = getContainer(containerName);
    const { resource } = await container.items.upsert<T>(document);
    return (resource || document) as T;
}

export async function deleteDocument(containerName: string, id: string, partitionKey?: string): Promise<void> {
    requireCosmosConfigured();
    const container = getContainer(containerName);
    await container.item(id, partitionKey || id).delete();
}

export function buildBaseDocument(type: string, payload: Record<string, unknown>, id?: string): TradingRecordDocument {
    const timestamp = nowIso();
    return {
        id: id || buildDocId(type, payload['profile_id'], payload['order_id'], payload['trade_id'], payload['user_id'], randomUUID()),
        productId: config.PRODUCT_ID,
        type,
        created_at: String(payload['created_at'] || timestamp),
        updated_at: String(payload['updated_at'] || timestamp),
        ...payload,
    };
}
