<?php

declare(strict_types=1);

namespace App\Http\Controllers\Project;

use App\Http\Controllers\Concerns\AuthorizesProjectAccess;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProjectOverviewResource;
use App\Models\Invoice;
use App\Services\ProjectProfitChartService;
use Illuminate\Http\Request;

class ProjectOverviewController extends Controller
{
    use AuthorizesProjectAccess;

    public function __construct(
        private readonly ProjectProfitChartService $profitChartService
    ) {}

    public function __invoke(Request $request): ProjectOverviewResource
    {
        $projects = $this->accessibleProjectsQuery()
            ->withApiRelations()
            ->with([
                'invoices' => fn ($query) => $query
                    ->whereIn('status', [Invoice::STATUS_PAID, Invoice::STATUS_APPROVED])
                    ->select(['id', 'project_id', 'type', 'total', 'status', 'issued_at', 'created_at']),
            ])
            ->get();

        $this->profitChartService->attachChartPoints($projects);

        $activeStatuses = ['active', 'approved', 'unsigned', 'waiting'];
        $completedStatuses = ['completed'];
        $portfolio = $this->profitChartService->portfolioSeries($projects);

        return new ProjectOverviewResource([
            'active_count' => $projects->whereIn('status', $activeStatuses)->count(),
            'completed_count' => $projects->whereIn('status', $completedStatuses)->count(),
            'total_investment' => (int) $projects->sum('budget'),
            'total_profit' => $portfolio['total_profit'],
            'profit_percent' => $portfolio['profit_percent'],
            'profit_series' => $portfolio['profit_series'],
            'loss_series' => $portfolio['loss_series'],
            'tooltip' => $portfolio['tooltip'],
            'projects' => $projects,
        ]);
    }
}
