<?php

namespace App\Models;

use Carbon\Carbon;
use App\Enum\TraderExperience;
use App\Enum\TraderStatus;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

class Trader extends Model
{
    protected $guarded = [];

    protected $casts = [
        'status' => TraderStatus::class,
        'experience' => TraderExperience::class,
    ];

    protected static function booted()
    {
        static::creating(function ($model) {
            $model->uuid = Str::uuid();
        });
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function copyTradeRequests()
    {
        return $this->hasMany(CopyTradeRequest::class);
    }

    public function copyTrades()
    {
        return $this->hasMany(CopyTrade::class);
    }

    public function performances()
    {
        return $this->hasMany(TraderPerformance::class)
            ->orderBy('recorded_at');
    }

    /**
     * Get the last 7 days of performance records for sparkline chart.
     */
    public function recentPerformances()
    {
        return $this->hasMany(TraderPerformance::class)
            ->where('recorded_at', '>=', Carbon::now()->subDays(7))
            ->orderBy('recorded_at', 'asc');
    }

    /**
     * Calculate total 7-day PnL percentage.
     * Positive = profitable, Negative = unprofitable.
     */
    public function sevenDayPnl(): float
    {
        $performances = $this->recentPerformances()->get();

        $total = 0;
        foreach ($performances as $perf) {
            $value = (float) $perf->roi_percentage;
            $total += $perf->direction->value === 'up' ? $value : -$value;
        }

        return round($total, 2);
    }
}
