<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Contracts\Repositories\PartnerInvestmentRepositoryInterface;
use App\Models\PartnerInvestment;
use Illuminate\Database\Eloquent\Collection;

final class EloquentPartnerInvestmentRepository implements PartnerInvestmentRepositoryInterface
{
    public function findById(int $id): ?PartnerInvestment
    {
        return PartnerInvestment::with(['partner', 'investmentProperty', 'distributions'])->find($id);
    }

    public function getByPartner(int $partnerId): Collection
    {
        return PartnerInvestment::where('partner_id', $partnerId)
            ->with(['investmentProperty', 'distributions'])
            ->latest()
            ->get();
    }

    public function getByProperty(int $propertyId): Collection
    {
        return PartnerInvestment::where('investment_property_id', $propertyId)
            ->with(['partner', 'distributions'])
            ->latest()
            ->get();
    }

    public function getByPartnerAndProperty(int $partnerId, int $propertyId): ?PartnerInvestment
    {
        return PartnerInvestment::where('partner_id', $partnerId)
            ->where('investment_property_id', $propertyId)
            ->with(['investmentProperty', 'distributions'])
            ->first();
    }

    public function getActiveByPartner(int $partnerId): Collection
    {
        return PartnerInvestment::active()
            ->where('partner_id', $partnerId)
            ->with(['investmentProperty', 'distributions'])
            ->latest()
            ->get();
    }

    public function create(array $data): PartnerInvestment
    {
        return PartnerInvestment::create($data);
    }

    public function update(int $id, array $data): PartnerInvestment
    {
        $investment = PartnerInvestment::findOrFail($id);
        $investment->update($data);

        return $investment->fresh();
    }

    public function getTotalInvestedByPartner(int $partnerId): float
    {
        return (float) PartnerInvestment::where('partner_id', $partnerId)
            ->where('status', 'active')
            ->sum('total_investment');
    }
}
