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

const PRESET_CONTAINER = 'strategy_presets';

interface StrategyPresetDocument {
    id: string;
    productId: string;
    type: 'strategy_preset';
    created_at?: string;
    [key: string]: unknown;
}

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

function getLegacyClient() {
    return getLegacySupabaseClient();
}

export async function listStrategyPresets(): Promise<any[]> {
    if (isCosmosConfigured()) {
        try {
            const container = getContainer(PRESET_CONTAINER);
            const { resources } = await container.items.query<StrategyPresetDocument>({
                query: 'SELECT * FROM c WHERE c.productId = @productId AND c.type = @type ORDER BY c.created_at DESC',
                parameters: [
                    { name: '@productId', value: config.PRODUCT_ID },
                    { name: '@type', value: 'strategy_preset' },
                ],
            }).fetchAll();
            if (resources.length > 0) {
                return resources;
            }
        } catch (error: any) {
            logger.error(`[StrategyPresetRepo] Cosmos preset lookup failed: ${error.message}`);
            return [];
        }
    }

    const client = getLegacyClient();
    if (!client) return [];

    try {
        const { data, error } = await client
            .from('strategy_presets')
            .select('*')
            .order('created_at', { ascending: false });

        if (error) {
            logger.error(`[StrategyPresetRepo] Preset lookup failed: ${error.message}`);
            return [];
        }

        const rows = data || [];
        if (isCosmosConfigured() && rows.length > 0) {
            try {
                const container = getContainer(PRESET_CONTAINER);
                await Promise.all(rows.map((row: any) => container.items.upsert<StrategyPresetDocument>({
                    id: String(row.id || row.original_profile_id || randomUUID()),
                    productId: config.PRODUCT_ID,
                    type: 'strategy_preset',
                    ...row,
                })));
            } catch (seedError: any) {
                logger.warn(`[StrategyPresetRepo] Cosmos preset seed failed: ${seedError.message}`);
            }
        }
        return rows;
    } catch (error: any) {
        logger.error(`[StrategyPresetRepo] Preset lookup unexpected error: ${error.message}`);
        return [];
    }
}

export async function createStrategyPreset(payload: Record<string, unknown>): Promise<void> {
    if (isCosmosConfigured()) {
        const container = getContainer(PRESET_CONTAINER);
        await container.items.upsert<StrategyPresetDocument>({
            id: String(payload.id || payload['original_profile_id'] || randomUUID()),
            productId: config.PRODUCT_ID,
            type: 'strategy_preset',
            created_at: String(payload['created_at'] || new Date().toISOString()),
            ...payload,
        });
    }

    const client = getLegacyClient();
    if (!client) {
        return;
    }

    const { error } = await client.from('strategy_presets').insert([payload]);
    if (error) {
        throw new Error(error.message);
    }
}
