#!/usr/bin/env bash
docker exec njts_backend bash -c 'cd /app && python3 << "EOF"
from app.core.database import get_connection

try:
    with get_connection() as conn:
        with conn.cursor() as cur:
            print("=" * 80)
            print("【逆仕訳データの検索と削除】")
            print("=" * 80)
            print()
            
            print("【ステップ1: 削除対象の逆仕訳を検索】")
            cur.execute("""
                SELECT 
                    je.journal_entry_id,
                    je.description,
                    je.entry_date,
                    je.created_at,
                    je.is_latest,
                    je.parent_entry_id
                FROM journal_entries je
                WHERE je.is_deleted = false
                AND je.is_latest = false
                AND je.parent_entry_id IS NULL
                AND je.original_entry_id IS NULL
                ORDER BY je.created_at DESC
            """)
            
            orphan_entries = cur.fetchall()
            print(f"削除対象の逆仕訳レコード: {len(orphan_entries)} 件")
            
            if orphan_entries:
                for entry in orphan_entries[:10]:
                    print(f"  ID={entry[\"journal_entry_id\"]}: {entry[\"description\"]} ({entry[\"entry_date\"]}, is_latest={entry[\"is_latest\"]})")
                
                print()
                print("【ステップ2: 逆仕訳を削除】")
                
                ids_to_delete = [e["journal_entry_id"] for e in orphan_entries]
                
                # Delete journal lines first
                cur.execute("DELETE FROM journal_lines WHERE journal_entry_id = ANY(%s)", (ids_to_delete,))
                lines_deleted = cur.rowcount
                
                # Delete journal entries
                cur.execute("DELETE FROM journal_entries WHERE journal_entry_id = ANY(%s)", (ids_to_delete,))
                entries_deleted = cur.rowcount
                
                conn.commit()
                print(f"削除完了: {entries_deleted} 仕訳レコード, {lines_deleted} 仕訳行")
            else:
                print("削除対象の逆仕訳がありません")
            
            print()
            print("【ステップ3: 削除後の統計】")
            cur.execute("SELECT COUNT(*) FROM journal_entries WHERE is_deleted = false")
            total = cur.fetchone()
            print(f"総レコード数: {total[\"count\"]}")
            
            cur.execute("SELECT COUNT(*) FROM journal_entries WHERE is_deleted = false AND is_latest = true")
            latest = cur.fetchone()
            print(f"is_latest=true: {latest[\"count\"]}")
            
            cur.execute("SELECT COUNT(*) FROM journal_entries WHERE is_deleted = false AND is_latest = false")
            old = cur.fetchone()
            print(f"is_latest=false: {old[\"count\"]}")
                
except Exception as e:
    print(f"エラー: {e}")
    import traceback
    traceback.print_exc()
EOF
'
