<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Currency;
use App\Helpers\RatesHelper;
use App\Models\Order;

class UpdateCurrencyRates extends Command
{
    protected $signature = 'currency:update-rates';
    protected $description = 'Update currency rates from external API';

    public function handle()
    {
        $ratesHelper = new RatesHelper();
        $rates = $ratesHelper->getRates();

        if (!$rates) {
            $this->error('Failed to fetch rates from API');
            return;
        }

        foreach ($rates as $code => $rateData) {
            $currency = Currency::where('code', $code)->first();
            
            if ($currency) {
                // Save current bid/ask as old_bid/old_ask before updating
                if ($currency->bid != $rateData['bid'] || $currency->ask != $rateData['ask']) {
                    $currency->old_bid = $currency->bid;
                    $currency->old_ask = $currency->ask;
                }
                
                // Update with new rates
                $currency->rate = $rateData['rate'] ?? null;
                $currency->bid = $rateData['bid'] ?? null;
                $currency->ask = $rateData['ask'] ?? null;
                
                $currency->save();
            }
        }

        // Check and close orders that have reached stop loss or take profit
        $orders = Order::where('status', 'open')
            ->get();

        foreach ($orders as $order) {
            if ($order->hasReachedStopLoss() || $order->hasReachedTakeProfit()) {
                $order->close();
                $this->info("Order #{$order->id} closed due to " . 
                    ($order->hasReachedStopLoss() ? "stop loss" : "take profit") . 
                    " being reached");
            }
        }

        $this->info('Currency rates updated successfully');
    }
} 