<?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\ProjectHubResource;
use App\Models\Project;
use App\Models\Report;
use Illuminate\Http\Request;

class ProjectHubController extends Controller
{
    use AuthorizesProjectAccess;

    public function __invoke(Request $request, Project $project): ProjectHubResource
    {
        $this->authorizeProjectAccess($project);

        $project->loadMissing('producer');

        $removedCount = Report::query()
            ->where('project_id', $project->id)
            ->where('type', Report::TYPE_HEALTH)
            ->where('report_type', Report::HEALTH_TYPE_REMOVE_PRODUCT)
            ->where('workflow_status', Report::WORKFLOW_APPROVED)
            ->count();

        $latestGrowth = Report::query()
            ->where('project_id', $project->id)
            ->where('type', Report::TYPE_GROWTH)
            ->where('workflow_status', Report::WORKFLOW_APPROVED)
            ->latest('report_at')
            ->first();

        $project->removed_products_count = $removedCount;
        $project->latest_growth_value = $latestGrowth?->metrics['current'] ?? null;
        $project->growth_target_value = $latestGrowth?->metrics['target'] ?? null;
        $project->growth_percent = $latestGrowth?->metrics['percent'] ?? 0;

        return new ProjectHubResource($project);
    }
}
