import assert from 'node:assert/strict';
import { supabaseService } from '../src/services/SupabaseService.js';

const MISSING_SOURCE_ERROR = "Could not find the 'source' column of 'trade_history' in the schema cache";

async function run() {
    const serviceAny = supabaseService as any;
    const originalClient = serviceAny.client;
    const originalSupportFlag = serviceAny.tradeHistorySupportsSource;

    const insertPayloads: any[] = [];
    let firstInsert = true;

    const mockClient = {
        from: (_table: string) => ({
            insert: async (rows: any[]) => {
                insertPayloads.push(rows?.[0]);
                if (firstInsert) {
                    firstInsert = false;
                    return { error: { message: MISSING_SOURCE_ERROR } };
                }
                return { error: null };
            }
        })
    };

    serviceAny.client = mockClient;
    serviceAny.tradeHistorySupportsSource = null;

    try {
        await supabaseService.logTransaction({
            user_id: 'user-1',
            profile_id: 'profile-1',
            symbol: 'BTC/USD',
            side: 'BUY',
            entry_price: 100,
            exit_price: 101,
            size: 1,
            pnl: 1,
            pnl_percent: 1,
            reason: 'test',
            timestamp: Date.now(),
            source: 'BOT'
        });

        assert.equal(insertPayloads.length, 2, 'Should retry transaction insert with legacy payload.');
        assert.equal(insertPayloads[0]?.source, 'BOT', 'First payload should include source column.');
        assert.equal('source' in insertPayloads[1], false, 'Fallback payload should omit source column.');
        assert.equal(serviceAny.tradeHistorySupportsSource, false, 'Support flag should switch to legacy mode after missing-column error.');

        insertPayloads.length = 0;
        await supabaseService.logTransaction({
            user_id: 'user-1',
            profile_id: 'profile-1',
            symbol: 'ETH/USD',
            side: 'BUY',
            entry_price: 100,
            exit_price: 102,
            size: 1,
            pnl: 2,
            pnl_percent: 2,
            reason: 'test-2',
            timestamp: Date.now(),
            source: 'BOT'
        });

        assert.equal(insertPayloads.length, 1, 'Legacy mode should avoid source insert attempt after detection.');
        assert.equal('source' in insertPayloads[0], false, 'Legacy-mode payload should omit source column.');
    } finally {
        serviceAny.client = originalClient;
        serviceAny.tradeHistorySupportsSource = originalSupportFlag;
    }

    console.log('[supabase-trade-history-fallback] OK: source-column fallback behavior validated');
}

await run();
