<?php

namespace App\Services;

use App\Models\Coin;
use App\Models\Wallet;
use App\Models\Transaction;
use Illuminate\Support\Collection;
use App\DTO\SwapResultDTO;
use App\Enums\TransactionType;

class SwapService
{
    public function prepareSwap($user): SwapResultDTO
    {
        $wallets = $user->wallets ?? collect([]);

        // Get last swap transaction
        $last = $user->transaction
            ->where('type', TransactionType::SWAP->value)
            ->sortByDesc('id')
            ->first();

        // 1) Determine source coin
        if ($last) {
            $defaultCoin = Coin::find($last->outgoing_wallet_id);
            $toCoin = Coin::find($last->incoming_wallet_id);
        } else {
            // cryptoCurrency is a SYMBOL
            $defaultCoin = Coin::where('symbol', $user->cryptoCurrency)->first();

            $fallbackWallet = $wallets->firstWhere('coin_id', '!=', optional($defaultCoin)->id);
            $toCoin = $fallbackWallet ? Coin::find($fallbackWallet->coin_id) : null;
        }

        // 2) If coin missing → return failure
        if (!$defaultCoin) {
            return SwapResultDTO::fail("Your default coin does not exist.");
        }

        // 3) Auto-create default wallet if missing
        $defaultWallet = $wallets->firstWhere('coin_id', $defaultCoin->id);

        if (!$defaultWallet) {
            $defaultWallet = Wallet::create([
                'user_id' => $user->id,
                'coin_id' => $defaultCoin->id,
                'balance' => 0,
            ]);
            $wallets->push($defaultWallet);
        }

        // 4) Auto-select or auto-create target coin
        if (!$toCoin) {
            // Pick ANY other coin the user has
            $toWalletCandidate = $wallets->firstWhere('coin_id', '!=', $defaultWallet->coin_id);
            if ($toWalletCandidate) {
                $toCoin = $toWalletCandidate->coin;
            } else {
                return SwapResultDTO::fail("You need at least two different coins to perform a swap.");
            }
        }

        // 5) Auto-create target wallet if missing
        $toWallet = $wallets->firstWhere('coin_id', $toCoin->id);

        if (!$toWallet) {
            $toWallet = Wallet::create([
                'user_id' => $user->id,
                'coin_id' => $toCoin->id,
                'balance' => 0,
            ]);
            $wallets->push($toWallet);
        }

        return SwapResultDTO::success(
            defaultWallet: $defaultWallet,
            toWallet: $toWallet,
            wallets: $wallets
        );
    }

    
    public function executeSwap(SwapResultDTO $dto)
    {

    }

    public function returnError($error): array
    {
        return ['status' => false, 'error' => $error];
    }
}
