<?php

declare(strict_types=1);

namespace App\Http\Controllers\Project;

use App\Http\Controllers\Concerns\AuthorizesProjectAccess;
use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Project;
use App\Services\ProjectProfitChartService;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProjectProfitChartController extends Controller
{
    use AuthorizesProjectAccess;

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

    public function show(Project $project): JsonResponse
    {
        $this->authorizeProjectAccess($project);

        $project->load([
            'invoices' => fn ($query) => $query
                ->whereIn('status', [Invoice::STATUS_PAID, Invoice::STATUS_APPROVED])
                ->select(['id', 'project_id', 'type', 'total', 'status', 'issued_at', 'created_at']),
        ]);

        return ApiResponse::success([
            'chart_points' => $this->profitChartService->chartPointsForProject($project),
        ]);
    }

    public function overview(Request $request): JsonResponse
    {
        $projects = $this->accessibleProjectsQuery()
            ->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();

        return ApiResponse::success(
            $this->profitChartService->portfolioSeries($projects)
        );
    }
}
