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

class ProjectTransactionController extends Controller
{
    use AuthorizesProjectAccess;

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

        $query = WalletTransaction::query()
            ->with(['invoice', 'payment'])
            ->where('project_id', $project->id);

        if ($request->filled('type')) {
            $query->where('type', $request->string('type'));
        }

        if ($request->filled('status')) {
            $query->where('status', $request->string('status'));
        }

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

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

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

        return WalletTransactionResource::collection(
            $request->boolean('noPaginate') ? $query->latest()->get() : $query->latest()->paginate($perPage)
        );
    }
}
