<?php

namespace App\Http\Controllers;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ReportingController extends Controller
{
    public function design(Request $request): JsonResponse
    {
        $validated = $this->validateQuery($request);

        return $this->forwardReportRequest(
            config('services.reporting.design_path'),
            $validated,
            'design'
        );
    }

    public function qa(Request $request): JsonResponse
    {
        $validated = $this->validateQuery($request);

        return $this->forwardReportRequest(
            config('services.reporting.qa_path'),
            $validated,
            'QA'
        );
    }

    private function validateQuery(Request $request): array
    {
        return $request->validate([
            'from_date' => ['required', 'date_format:d/m/Y'],
            'to_date' => ['required', 'date_format:d/m/Y'],
            'page' => ['nullable', 'integer', 'min:1'],
            'per_page' => ['nullable', 'integer', 'min:1', 'max:200'],
        ]);
    }

    private function forwardReportRequest(?string $path, array $query, string $label): JsonResponse
    {
        $baseUrl = rtrim((string) config('services.reporting.base_url'), '/');
        $token = (string) config('services.reporting.token');
        $timeout = (int) config('services.reporting.timeout', 30);

        if ($baseUrl === '' || $path === null || $path === '') {
            return response()->json([
                'message' => "The {$label} reporting endpoint is not configured.",
            ], 500);
        }

        if ($token === '') {
            return response()->json([
                'message' => 'The reporting API token is not configured.',
            ], 500);
        }

        try {
            $response = Http::baseUrl($baseUrl)
                ->acceptJson()
                ->timeout($timeout)
                ->withToken($token)
                ->get(ltrim($path, '/'), $query);

            if ($response->failed()) {
                return response()->json([
                    'message' => "Unable to load the {$label} reporting data.",
                    'upstream_status' => $response->status(),
                    'upstream_body' => $response->json() ?? $response->body(),
                ], 502);
            }

            return response()->json(
                $response->json(),
                $response->status()
            );
        } catch (ConnectionException|RequestException $exception) {
            return response()->json([
                'message' => "Unable to reach the {$label} reporting service.",
            ], 502);
        }
    }
}
