<?php

declare(strict_types=1);

namespace App\Http\Controllers\Project;

use App\Http\Controllers\Concerns\AuthorizesProjectAccess;
use App\Http\Controllers\Controller;
use App\Http\Requests\Project\ProjectListRequest;
use App\Http\Resources\ProjectSummaryResource;
use App\Models\Invoice;
use App\Services\ProjectProfitChartService;
use Illuminate\Pagination\AbstractPaginator;

class ProjectHistoryController extends Controller
{
    use AuthorizesProjectAccess;

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

    public function __invoke(ProjectListRequest $request)
    {
        $query = $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']),
            ])
            ->whereIn('status', ['completed', 'cancelled', 'expired']);

        if ($request->filled('q')) {
            $search = $request->string('q');
            $query->where(function ($scope) use ($search): void {
                $scope->where('name', 'like', "%{$search}%")
                    ->orWhere('code', 'like', "%{$search}%");
            });
        }

        if ($request->filled('from')) {
            $query->whereDate('end_date', '>=', $request->date('from'));
        }

        if ($request->filled('to')) {
            $query->whereDate('end_date', '<=', $request->date('to'));
        }

        $perPage = min($request->integer('per_page', 15), 50);

        $projects = $request->boolean('noPaginate')
            ? $query->get()
            : $query->paginate($perPage);

        $this->profitChartService->attachChartPoints(
            $projects instanceof AbstractPaginator
                ? $projects->getCollection()
                : $projects
        );

        return ProjectSummaryResource::collection($projects);
    }
}
