<?php

namespace App\Nexus\Models;

use Illuminate\Database\Eloquent\Model;

class NexusEconomySnapshot extends Model
{
    protected $table = 'nexus_economy_snapshots';

    public $timestamps = false;

    protected $fillable = [
        'nexus_session_id',
        'snapshot_type',
        'total_pending_sell_value',
        'total_active_investment',
        'platform_liquidity',
        'recess_threshold',
        'excess_threshold',
        'market_breakdown',
        'captured_at',
    ];

    protected $casts = [
        'total_pending_sell_value' => 'decimal:2',
        'total_active_investment'  => 'decimal:2',
        'platform_liquidity'       => 'decimal:2',
        'recess_threshold'         => 'decimal:2',
        'excess_threshold'         => 'decimal:2',
        'market_breakdown'         => 'array',
        'captured_at'              => 'datetime',
    ];

    const TYPE_SESSION_START = 'session_start';
    const TYPE_SESSION_END   = 'session_end';
    const TYPE_MANUAL        = 'manual';

    // ─── RELATIONSHIPS ───

    public function session()
    {
        return $this->belongsTo(NexusSession::class, 'nexus_session_id');
    }

    // ─── SCOPES ───

    public function scopeSessionStart($query)
    {
        return $query->where('snapshot_type', self::TYPE_SESSION_START);
    }

    public function scopeSessionEnd($query)
    {
        return $query->where('snapshot_type', self::TYPE_SESSION_END);
    }

    // ─── HELPERS ───

    /**
     * Calculate recess/excess thresholds from asking price and config.
     * Recess/excess are calculated on asking price, not product price.
     */
    public static function calculateThresholds(float $askingPrice): array
    {
        $recessPct = NexusConfig::getRecessThreshold();
        $excessPct = NexusConfig::getExcessThreshold();

        return [
            'recess' => $askingPrice * (1 - $recessPct / 100),
            'excess' => $askingPrice * (1 + $excessPct / 100),
        ];
    }

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            if (empty($model->captured_at)) {
                $model->captured_at = now();
            }
        });
    }
}
