<?php

namespace App\Http\Controllers\Api\V1\Workflow;

use App\Domain\Workflow\Models\Pipeline;
use App\Domain\Workflow\Requirements\RequirementRegistry;
use App\Http\Controllers\Controller;
use App\Http\Resources\PipelineStageResource;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PipelineController extends Controller
{
    public function __construct(private readonly RequirementRegistry $requirements) {}

    public function index(Request $request): JsonResponse
    {
        abort_unless($request->user()->can('pipeline.view'), 403);

        $pipelines = Pipeline::query()
            ->where('company_id', $request->user()->company_id)
            ->when(! $request->boolean('include_inactive'), fn ($q) => $q->where('is_active', true))
            ->with('stages')
            ->orderByDesc('is_default')
            ->orderBy('name')
            ->get();

        return ApiResponse::success(
            $pipelines->map(fn (Pipeline $pipeline) => [
                'id' => $pipeline->uuid,
                'code' => $pipeline->code,
                'name' => $pipeline->name,
                'description' => $pipeline->description,
                'destination_country' => $pipeline->destination_country,
                'is_default' => $pipeline->is_default,
                'is_active' => $pipeline->is_active,
                'stages' => PipelineStageResource::collection($pipeline->stages),
            ]),
            meta: [
                // Lets the admin UI offer only requirements the server knows.
                'requirement_types' => array_map(
                    fn ($requirement) => [
                        'type' => $requirement->type(),
                        'description' => $requirement->describe([]),
                    ],
                    array_values($this->requirements->all()),
                ),
            ],
        );
    }
}
