<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class TransactionController extends Controller
{
    public function destroy(Transaction $transaction)
    {
        // Special rule: Cannot delete a settled borrow directly. Must delete settlement first.
        if ($transaction->type === Transaction::TYPE_BORROW && $transaction->borrow_settled_at) {
            return back()->with('error', 'Cannot delete a settled borrow. Please delete the settlement transaction first.');
        }

        $type = $transaction->type;
        DB::transaction(function () use ($transaction) {
            $currency = $transaction->currency;

            // 1. Reverse balance effects
            $transaction->reverseBalanceEffects();

            // 2. Revert agent balance status to pending if linked
            $agentBalance = \App\Models\AgentBalance::where('transaction_id', $transaction->id)->first();
            if ($agentBalance) {
                $agentBalance->update([
                    'is_received' => false,
                    'received_at' => null,
                    'transaction_id' => null,
                ]);
            }

            // 3. Delete the transaction
            $transaction->delete();

            // 3. Recalculate profits for the currency (if it was a buy/borrow/settlement)
            if (in_array($transaction->type, [Transaction::TYPE_BUY, Transaction::TYPE_BORROW, Transaction::TYPE_SETTLEMENT, Transaction::TYPE_OPENING_BALANCE])) {
                $currency->recalculateProfits();
            }
        });

        if ($type === Transaction::TYPE_BORROW) {
            return redirect()->route('borrows.index')->with('success', 'Borrow transaction deleted and balances reversed successfully.');
        }

        if ($type === Transaction::TYPE_ADJUSTMENT) {
            return redirect()->route('accounts.adjust.index')->with('success', 'Adjustment deleted and balances reversed successfully.');
        }

        return redirect()->back()->with('success', 'Transaction deleted and balances reversed successfully.');
    }
}
