-- Reset expenses that were marked as paid but had no successful CSV export
-- This fixes the issue where expenses were marked as paid even when export failed

-- Find expenses with the failed export reference
-- Reference format: CSV_EXPORT_20251210_132341_c5cf92be-4172-4fe2-af5c-f05d83b3a938

-- Reset the specific expenses from the failed export
UPDATE ticket_expenses
SET 
    is_paid = false,
    paid_at = NULL,
    paid_to_user_id = NULL,
    payment_reference = NULL,
    updated_at = timezone('utc'::text, now())
WHERE 
    payment_reference = 'CSV_EXPORT_20251210_132341_c5cf92be-4172-4fe2-af5c-f05d83b3a938'
    AND is_paid = true
    AND deleted_at IS NULL;

-- Verify the reset
SELECT 
    id,
    incurred_by_user_id,
    total_cost,
    is_approved,
    is_paid,
    payment_reference,
    expense_date
FROM ticket_expenses
WHERE 
    id IN ('35db9201-3c05-4853-be91-5eb6f30782d1', 'd73cb843-e4fb-4200-aa3e-243887714422')
    AND deleted_at IS NULL;
