<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Http\Requests\VerifyCacRequest;
use App\Services\CacVerificationApiService;
use Illuminate\Http\JsonResponse;

class CacVerificationController extends Controller
{
    public function __construct(
        private readonly CacVerificationApiService $cacVerificationApiService,
    ) {}

    /**
     * Verify a company via CAC Basic lookup.
     * Used for public, portal, and admin routes — auth is enforced at the route level.
     */
    public function verify(VerifyCacRequest $request): JsonResponse
    {
        $result = $this->cacVerificationApiService->verifyCompany(
            $request->validated('rc_number'),
            $request->validated('company_type'),
        );

        if (! $result['success']) {
            $serviceDown = $result['service_unavailable'] ?? false;
            $status = $serviceDown ? 503 : 422;
            return response()->json(array_filter([
                'success'      => false,
                'service_down' => $serviceDown ?: null,
                'message'      => $result['message'],
            ]), $status);
        }

        return response()->json([
            'success' => true,
            'message' => $result['message'],
            'data'    => $result['data'],
        ]);
    }
}
