<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

final class PartnerInvestment extends Model
{
    use HasFactory;

    protected $fillable = [
        'partner_id',
        'investment_property_id',
        'shares_purchased',
        'total_investment',
        'purchase_date',
        'status',
    ];

    protected function casts(): array
    {
        return [
            'partner_id' => 'integer',
            'investment_property_id' => 'integer',
            'shares_purchased' => 'integer',
            'total_investment' => 'decimal:2',
            'purchase_date' => 'datetime',
        ];
    }

    public function partner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'partner_id');
    }

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

    public function distributions(): HasMany
    {
        return $this->hasMany(PartnerDistribution::class, 'investment_id');
    }

    /**
     * Scope to get active investments
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Get total distributions received
     */
    public function totalDistributions(): float
    {
        return (float) $this->distributions()
            ->where('payment_status', 'processed')
            ->sum('distribution_amount');
    }

    /**
     * Calculate ROI percentage
     */
    public function roi(): float
    {
        if ($this->total_investment == 0) {
            return 0;
        }

        return ($this->totalDistributions() / $this->total_investment) * 100;
    }
}
