<?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 CprMonitoringUpdateController
{
    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())
                ->key('preview', val::optional(val::boolType()), false)
                ->key('description', val::optional(val::stringType()->notEmpty()->length(1, 5000)), false)
                ->key('link', val::optional(val::stringType()->notEmpty()->length(1, 2048)), false)
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail('Validation failed: ' . $e->getFullMessage(), [], 'E_VALIDATE')->withStatus(400);
        }

        $id = (int)$body['id'];
        $preview = array_key_exists('preview', $body) ? (bool)$body['preview'] : null;
        $description = array_key_exists('description', $body) ? (string)$body['description'] : null;
        $link = array_key_exists('link', $body) ? (string)$body['link'] : null;

        if ($preview === null && $description === null && $link === null) {
            return ResponseLib::sendFail('Validation failed: nothing to update', [], 'E_VALIDATE')->withStatus(400);
        }

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

        return $updated
            ? ResponseLib::sendOk($updated, 'S_UPDATED')
            : ResponseLib::sendFail('Cpr monitoring Not Found or Not Updated', [], 'E_DATABASE')->withStatus(204);
    }
}
