-- Fix Backtest FinalPnl where it incorrectly equals NetPnl
-- This script updates records where FinalPnl was incorrectly set to the same value as NetPnl
-- Correct formula: FinalPnl = NetPnl + Fees (since NetPnl = FinalPnl - Fees)
--
-- IMPORTANT: Run this script in a transaction and verify results before committing!
-- Usage: psql -h <host> -U <user> -d <database> -f fix-backtest-finalpnl.sql

BEGIN;

-- First, let's see how many records will be affected
SELECT 
    COUNT(*) as affected_records,
    SUM("Fees") as total_fees_to_add,
    AVG("Fees") as avg_fees
FROM "Backtests"
WHERE "FinalPnl" = "NetPnl" 
  AND "Fees" > 0;

-- Show sample of records that will be updated (for verification)
SELECT 
    "Id",
    "Identifier",
    "FinalPnl" as current_final_pnl,
    "NetPnl",
    "Fees",
    ("NetPnl" + "Fees") as new_final_pnl,
    ("NetPnl" + "Fees" - "FinalPnl") as change_amount
FROM "Backtests"
WHERE "FinalPnl" = "NetPnl" 
  AND "Fees" > 0
ORDER BY "Id"
LIMIT 10;

-- Update the records where FinalPnl equals NetPnl
-- Only update if Fees > 0 to avoid incorrect updates
UPDATE "Backtests"
SET 
    "FinalPnl" = "NetPnl" + "Fees",
    "UpdatedAt" = NOW()
WHERE "FinalPnl" = "NetPnl" 
  AND "Fees" > 0;

-- Verify the update - should return 0
SELECT 
    COUNT(*) as remaining_incorrect_records
FROM "Backtests"
WHERE "FinalPnl" = "NetPnl" 
  AND "Fees" > 0;

-- Show a sample of updated records to verify
SELECT 
    "Id",
    "Identifier",
    "FinalPnl" as new_final_pnl,
    "NetPnl",
    "Fees",
    ("FinalPnl" - "NetPnl") as difference_should_equal_fees
FROM "Backtests"
WHERE "FinalPnl" != "NetPnl" 
  AND "Fees" > 0
ORDER BY "UpdatedAt" DESC
LIMIT 10;

-- If everything looks correct, uncomment the COMMIT line below
-- COMMIT;

-- If something is wrong, run ROLLBACK instead
-- ROLLBACK;

