<?php

namespace Tests\Feature;

use App\Filament\Pages\DonorInformationDashboard;
use App\Models\DonorFinancialPortfolio;
use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class DonorInformationDashboardTest extends TestCase
{
    use RefreshDatabase;

    public function test_donor_information_dashboard_can_be_rendered()
    {
        // Create a user
        $user = User::factory()->create();

        // Create a donor financial portfolio
        $portfolio = DonorFinancialPortfolio::factory()->create([
            'name' => 'Test Portfolio',
            'balance' => 10000.00,
        ]);

        // Create an order linked to the portfolio
        $order = Order::factory()->create([
            'status' => Order::STATUS_LAUNCHED,
            'number_of_families' => 50,
        ]);

        // Link the order to the portfolio
        $portfolio->orders()->attach($order->id, ['allocated_amount' => 5000.00]);

        // Test that the dashboard page class exists and can get navigation label
        $this->assertIsString(DonorInformationDashboard::getNavigationLabel());

        // Test that widgets can be retrieved
        $dashboard = new DonorInformationDashboard;
        $widgets = $dashboard->getWidgets();

        $this->assertIsArray($widgets);
        $this->assertCount(2, $widgets);
    }

    public function test_widgets_calculate_stats_correctly()
    {
        // Create portfolios
        DonorFinancialPortfolio::factory()->count(3)->create([
            'balance' => 5000.00,
        ]);

        // Create orders
        $orders = Order::factory()->count(2)->create([
            'status' => Order::STATUS_LAUNCHED,
            'number_of_families' => 25,
        ]);

        // Link orders to portfolios
        $portfolio = DonorFinancialPortfolio::first();
        foreach ($orders as $order) {
            $portfolio->orders()->attach($order->id, ['allocated_amount' => 1000.00]);
        }

        // The stats should calculate correctly
        $totalPortfolioValue = DonorFinancialPortfolio::sum('balance'); // 15000
        $supportedProjectsCount = Order::whereHas('donorFinancialPortfolios')->count(); // 2
        $totalBeneficiaryFamilies = Order::where('status', Order::STATUS_LAUNCHED)
            ->whereHas('donorFinancialPortfolios')
            ->sum('number_of_families'); // 50

        $this->assertEquals(15000.00, $totalPortfolioValue);
        $this->assertEquals(2, $supportedProjectsCount);
        $this->assertEquals(50, $totalBeneficiaryFamilies);
    }
}
