<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Investment extends Model
{
    protected $fillable = [
        'user_id',
        'wallet_id',
        'package_id',
        'principal_amount',
        'expected_return_amount',
        'currency_code',
        'duration_days',
        'duration_hours',
        'started_at',
        'matures_at',
        'claimed_at',
        'status',
        'is_active',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'principal_amount' => 'decimal:4',
            'expected_return_amount' => 'decimal:4',
            'duration_days' => 'integer',
            'duration_hours' => 'integer',
            'started_at' => 'datetime',
            'matures_at' => 'datetime',
            'claimed_at' => 'datetime',
            'is_active' => 'boolean',
        ];
    }

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

    public function wallet(): BelongsTo
    {
        return $this->belongsTo(Wallet::class);
    }

    public function package(): BelongsTo
    {
        return $this->belongsTo(InvestmentPackage::class, 'package_id');
    }

    /**
     * Accrued amount based on hourly progress (for package-based investments).
     */
    public function getAccruedAmountAttribute(): float
    {
        $principal = (float) $this->principal_amount;
        $expected = (float) $this->expected_return_amount;
        $durationHours = (int) ($this->duration_hours ?? 0);

        if ($durationHours <= 0) {
            return $principal;
        }

        $elapsed = (int) min(
            $this->started_at->diffInHours(now(), false),
            $durationHours
        );

        if ($elapsed <= 0) {
            return $principal;
        }

        return $principal + ($expected - $principal) * ($elapsed / $durationHours);
    }

    /**
     * Progress ratio 0..1 for display (hourly-based for package subscriptions).
     */
    public function getProgressRatioAttribute(): float
    {
        $durationHours = (int) ($this->duration_hours ?? 0);
        if ($durationHours <= 0) {
            return 0;
        }
        $elapsed = (int) min(
            $this->started_at->diffInHours(now(), false),
            $durationHours
        );

        return $elapsed / $durationHours;
    }
}
