<?php

namespace Controllers;

use Libs\ResponseLib;
use Psr\Http\Message\ServerRequestInterface;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as val;
use Services\CprMonitoringService;

class CprMonitoringGetController
{
    private CprMonitoringService $service;

    public function __construct()
    {
        $this->service = new CprMonitoringService();
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $userId = (int)($request->getAttribute('api_user_id') ?? 0);
        $companyId = (int)($request->getAttribute('api_company_id') ?? 0);

        if ($userId <= 0 || $companyId <= 0) {
            return ResponseLib::sendFail('Unauthorized', [], 'E_VALIDATE')->withStatus(401);
        }

        $body = json_decode((string)$request->getBody(), true) ?? [];

        try {
            val::key('id', val::intType()->positive())
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail('Validation failed: ' . $e->getFullMessage(), [], 'E_VALIDATE')->withStatus(400);
        }

        $id = (int)$body['id'];

        try {
            $row = $this->service->getById($id);
        } catch (\InvalidArgumentException $e) {
            return ResponseLib::sendFail($e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Failed to fetch cpr monitoring: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }

        return $row
            ? ResponseLib::sendOk($row)
            : ResponseLib::sendFail('Cpr monitoring not found', [], 'E_NOT_FOUND')->withStatus(404);
    }
}
