<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Contracts\Repositories\InvestmentPerformanceRepositoryInterface;
use App\Models\InvestmentPerformance;
use Illuminate\Database\Eloquent\Collection;

final class EloquentInvestmentPerformanceRepository implements InvestmentPerformanceRepositoryInterface
{
    public function findById(int $id): ?InvestmentPerformance
    {
        return InvestmentPerformance::with('investmentProperty')->find($id);
    }

    public function getByProperty(int $propertyId): Collection
    {
        return InvestmentPerformance::where('investment_property_id', $propertyId)
            ->latest('reporting_period')
            ->get();
    }

    public function getByPeriod(int $propertyId, string $startDate, string $endDate): Collection
    {
        return InvestmentPerformance::where('investment_property_id', $propertyId)
            ->whereBetween('reporting_period', [$startDate, $endDate])
            ->latest('reporting_period')
            ->get();
    }

    public function getLatestByProperty(int $propertyId): ?InvestmentPerformance
    {
        return InvestmentPerformance::where('investment_property_id', $propertyId)
            ->latest('reporting_period')
            ->first();
    }

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

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

        return $performance->fresh();
    }

    public function delete(int $id): bool
    {
        return InvestmentPerformance::destroy($id) > 0;
    }

    public function getAverageOccupancyRate(int $propertyId): float
    {
        return (float) InvestmentPerformance::where('investment_property_id', $propertyId)
            ->avg('occupancy_rate') ?? 0.0;
    }

    public function getTotalRevenue(int $propertyId): float
    {
        return (float) InvestmentPerformance::where('investment_property_id', $propertyId)
            ->sum('total_revenue');
    }
}
