<?php

namespace App\Http\Controllers\Agent;

use App\Http\Controllers\ApiController;
use App\Models\Agent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

class StatusController extends ApiController
{
    public function __invoke(Request $request): JsonResponse
    {
        try {
            $apiKey = $request->header('API-Key') ?? $request->query('apiKey');
            if (!$apiKey) {
                return $this->error('API-Key is required', status: Response::HTTP_BAD_REQUEST);
            }

            $agent = Agent::query()->with('admin')->where('id', $apiKey)->first();
            if (!$agent) {
                return $this->error('Agent not found', status: Response::HTTP_BAD_REQUEST);
            }

            if ($agent->admin && $agent->admin->is_active === false) {
                return $this->error('Account is disabled', status: Response::HTTP_FORBIDDEN);
            }

            return $this->success([
                'agent_id'    => $agent->id,
                'admin_id'    => $agent->admin_id,
                'admin_active'=> $agent->admin ? (bool) $agent->admin->is_active : null,
            ]);
        } catch (Throwable $e) {
            return $this->error($e->getMessage(), status: $e->getCode() ?: Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}
