<?php

namespace App\Services;

use App\Models\Investment;
use App\Models\Investor;

class InvestorService
{
    /**
     * Get or create investor from investment data
     */
    public function getOrCreateFromInvestment(Investment $investment): Investor
    {
        return Investor::findOrCreateByEmail($investment->email, [
            'full_name' => $investment->investor_name,
            'phone' => $investment->phone,
            'country' => $investment->country,
            'investor_type' => $investment->investor_type,
        ]);
    }

    /**
     * Link investment to investor
     */
    public function linkInvestment(Investment $investment): Investor
    {
        $investor = $this->getOrCreateFromInvestment($investment);

        $investment->update(['investor_id' => $investor->id]);

        // Update aggregates
        $investor->updateAggregates();

        return $investor;
    }

    /**
     * Calculate total returns for an investor
     */
    public function calculateReturns(Investor $investor): array
    {
        $investments = $investor->investments()
            ->where('payment_status', 'confirmed')
            ->get();

        $totalInvested = $investments->sum('investment_amount');
        $totalExpectedReturns = 0;
        $totalActualReturns = $investor->dividendPayments()->completed()->sum('amount');

        foreach ($investments as $investment) {
            $totalExpectedReturns += $investment->calculateExpectedReturns();
        }

        return [
            'total_invested' => round($totalInvested, 2),
            'total_expected_returns' => round($totalExpectedReturns, 2),
            'total_actual_returns' => round($totalActualReturns, 2),
            'roi_percentage' => $totalInvested > 0 
                ? round(($totalActualReturns / $totalInvested) * 100, 2) 
                : 0,
            'investments_count' => $investments->count(),
        ];
    }

    /**
     * Get investment history for an investor
     */
    public function getInvestmentHistory(Investor $investor): array
    {
        $investments = $investor->investments()
            ->orderByDesc('created_at')
            ->get()
            ->map(function ($investment) {
                return [
                    'id' => $investment->id,
                    'reference' => $investment->reference,
                    'tier' => $investment->investment_tier,
                    'amount' => $investment->investment_amount,
                    'currency' => $investment->currency,
                    'term' => $investment->investment_term,
                    'status' => $investment->status,
                    'payment_status' => $investment->payment_status,
                    'expected_roi' => $investment->getExpectedRoi(),
                    'expected_returns' => $investment->calculateExpectedReturns(),
                    'created_at' => $investment->created_at,
                    'payment_completed_at' => $investment->payment_completed_at,
                ];
            });

        return [
            'investments' => $investments,
            'summary' => [
                'total_count' => $investments->count(),
                'total_invested' => $investments->sum('amount'),
                'active_count' => $investments->where('status', 'active')->count(),
            ],
        ];
    }

    /**
     * Get dividend history for an investor
     */
    public function getDividendHistory(Investor $investor): array
    {
        $dividends = $investor->dividendPayments()
            ->orderByDesc('year')
            ->orderByDesc('quarter')
            ->get()
            ->map(function ($dividend) {
                return [
                    'id' => $dividend->id,
                    'period' => $dividend->getPeriodLabel(),
                    'amount' => $dividend->amount,
                    'currency' => $dividend->currency,
                    'status' => $dividend->status,
                    'paid_at' => $dividend->paid_at,
                    'investment_reference' => $dividend->investment->reference ?? null,
                ];
            });

        return [
            'dividends' => $dividends,
            'summary' => [
                'total_payments' => $dividends->count(),
                'total_amount' => $dividends->where('status', 'completed')->sum('amount'),
                'pending_amount' => $dividends->where('status', 'pending')->sum('amount'),
            ],
        ];
    }

    /**
     * Update investor profile
     */
    public function updateProfile(Investor $investor, array $data): Investor
    {
        $allowedFields = [
            'full_name',
            'phone',
            'country',
            'risk_profile',
            'communication_preferences',
        ];

        $updateData = array_intersect_key($data, array_flip($allowedFields));

        $investor->update($updateData);

        return $investor->fresh();
    }
}
