<?php

namespace App\Models;

use App\Enums\InvestmentStatus;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[Fillable([
    'user_id',
    'amount',
    'capital_balance',
    'months_credited',
    'duration_months',
    'monthly_return_snapshot',
    'txid',
    'status',
    'confirmed_at',
    'maturity_at',
    'accrual_through_date',
    'confirmed_by',
])]
class Investment extends Model
{
    /**
     * @return BelongsTo<User, Investment>
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * @return BelongsTo<User, Investment>
     */
    public function confirmer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'confirmed_by');
    }

    /**
     * @return HasMany<InvestmentMonthReturn, Investment>
     */
    public function monthlyReturns(): HasMany
    {
        return $this->hasMany(InvestmentMonthReturn::class)->orderBy('month_index');
    }

    /**
     * @return HasMany<InvestmentTransaction, Investment>
     */
    public function transactions(): HasMany
    {
        return $this->hasMany(InvestmentTransaction::class)->orderBy('id');
    }

    /**
     * @return HasMany<WithdrawalRequest, Investment>
     */
    public function withdrawalRequests(): HasMany
    {
        return $this->hasMany(WithdrawalRequest::class)->orderByDesc('created_at');
    }

    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
            'capital_balance' => 'decimal:2',
            'monthly_return_snapshot' => 'decimal:2',
            'status' => InvestmentStatus::class,
            'confirmed_at' => 'datetime',
            'maturity_at' => 'datetime',
            'accrual_through_date' => 'date',
            'months_credited' => 'integer',
        ];
    }
}
