<?php

namespace App\Services\Bot;

use App\Models\Position;
use App\Models\User;

class PositionMonitorService
{
    public function __construct(
        private ExitEngine $exitEngine,
        private PositionSyncService $positionSync,
    ) {}

    public function onTick(User $user, string $token, float $ltp): void
    {
        $positions = Position::query()
            ->where('user_id', $user->id)
            ->where('is_open', true)
            ->whereHas('instrument', fn ($q) => $q->where('token', $token))
            ->get();

        $rulebook = $user->strategy?->rulebook ?? config('rulebook');

        foreach ($positions as $position) {
            $this->positionSync->recalculateUnrealized($position, $ltp);
            $reason = $this->exitEngine->evaluate($position->fresh(), $ltp, $rulebook);

            if ($reason) {
                $this->exitEngine->executeExit($user, $position->fresh(), $reason, $rulebook);
            }
        }
    }

    public function onOrderFill(User $user): void
    {
        $this->positionSync->syncUser($user);
    }
}
