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

        $cprId = (int)$body['cpr_id'];
        $preview = isset($body['preview']) ? (bool)$body['preview'] : false;
        $description = (string)$body['description'];
        $link = (string)$body['link'];

        try {
            $created = $this->service->create($cprId, $preview, $description, $link);
        } catch (\InvalidArgumentException $e) {
            return ResponseLib::sendFail($e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
        } catch (\PDOException $e) {
            if (($e->getCode() ?? '') === '23503') {
                return ResponseLib::sendFail('CPR not found', ['cpr_id' => $cprId], 'E_NOT_FOUND')->withStatus(404);
            }
            return ResponseLib::sendFail('Failed to create cpr monitoring: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Failed to create cpr monitoring: ' . $e->getMessage(), [], 'E_INTERNAL')->withStatus(500);
        }

        return ResponseLib::sendOk($created, 'S_CREATED');
    }
}
