import { getContainer } from '@bytelyst/cosmos';
import { config } from '../config/index.js';
import logger from '../utils/logger.js';
import { loadLatestLegacyBotStateSnapshot, saveLegacyBotStateSnapshot } from './legacySupabaseClient.js';
import { listActiveTradingUsers } from './userRepository.js';

const CONTAINER_NAME = 'bot_state_snapshots';

interface BotStateSnapshotDocument {
    id: string;
    productId: string;
    ownerId: string;
    state: unknown;
    updatedAt: string;
}

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

function isUuid(value: string): boolean {
    return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
}

function buildSnapshotId(ownerId: string): string {
    return `${config.PRODUCT_ID}:${ownerId}`;
}

export async function resolveSnapshotOwnerId(): Promise<string | null> {
    const configured = String(config.SNAPSHOT_USER_ID || '').trim().toLowerCase();
    if (isUuid(configured)) {
        return configured;
    }

    const users = await listActiveTradingUsers();
    const firstUserId = String(users[0]?.user_id || '').trim().toLowerCase();
    if (isUuid(firstUserId)) {
        return firstUserId;
    }

    return null;
}

export async function loadLatestBotStateSnapshot(
    ownerId: string
): Promise<{ state: unknown } | null> {
    if (!ownerId) return null;

    const loadLegacySnapshot = async () => loadLatestLegacyBotStateSnapshot(ownerId);

    if (!isCosmosConfigured()) {
        return loadLegacySnapshot();
    }

    if (isCosmosConfigured()) {
        try {
            const container = getContainer(CONTAINER_NAME);
            const { resource } = await container
                .item(buildSnapshotId(ownerId), config.PRODUCT_ID)
                .read<BotStateSnapshotDocument>();
            if (resource?.state !== undefined) {
                return { state: resource.state };
            }
            const legacySnapshot = await loadLegacySnapshot();
            if (!legacySnapshot) {
                return null;
            }
            await container.items.upsert<BotStateSnapshotDocument>({
                id: buildSnapshotId(ownerId),
                productId: config.PRODUCT_ID,
                ownerId,
                state: legacySnapshot.state,
                updatedAt: new Date().toISOString()
            });
            logger.info(`[Snapshots] Seeded snapshot for owner ${ownerId} from legacy store into Cosmos.`);
            return legacySnapshot;
        } catch (error) {
            const code = (error as { code?: number })?.code;
            if (code !== 404) {
                logger.warn(`[Snapshots] Cosmos load/seed failed for ${ownerId}: ${error instanceof Error ? error.message : 'unknown error'}`);
            }
            return null;
        }
    }
    return null;
}

export async function saveBotStateSnapshot(
    ownerId: string,
    state: unknown
): Promise<void> {
    if (!ownerId) return;

    if (isCosmosConfigured()) {
        try {
            const container = getContainer(CONTAINER_NAME);
            const doc: BotStateSnapshotDocument = {
                id: buildSnapshotId(ownerId),
                productId: config.PRODUCT_ID,
                ownerId,
                state,
                updatedAt: new Date().toISOString()
            };
            await container.items.upsert(doc);
            return;
        } catch (error) {
            logger.warn(`[Snapshots] Cosmos upsert failed, falling back to legacy store: ${error instanceof Error ? error.message : 'unknown error'}`);
        }
    }

    await saveLegacyBotStateSnapshot(ownerId, state);
}
