<?php

namespace Controllers;

use Libs\ResponseLib;
use Models\TshieldWebhookModel;
use Psr\Http\Message\ServerRequestInterface;

class TshieldWebhookController
{
    private TshieldWebhookModel $model;

    public function __construct()
    {
        $this->model = new TshieldWebhookModel();
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $body = json_decode((string)$request->getBody(), true);

        if (!is_array($body)) {
            return ResponseLib::sendFail('Invalid JSON payload.', [], 'E_VALIDATE')->withStatus(400);
        }

        $statusDescription = $body['status']['status'] ?? null;
        if ($statusDescription !== 'Aprovado') {
            return ResponseLib::sendOk([
                'processed' => false,
                'reason' => 'Status not approved. No action taken.',
            ], 'S_IGNORED');
        }

        $externalNumber = $body['number'] ?? $body['token'] ?? null;
        if (!is_string($externalNumber) || trim($externalNumber) === '') {
            return ResponseLib::sendFail('Missing analysis number/token in payload.', [], 'E_VALIDATE')->withStatus(400);
        }

        $updated = $this->model->approveByExternalId($externalNumber);
        if (!$updated) {
            return ResponseLib::sendFail(
                'No user found for provided analysis number.',
                ['number' => $externalNumber],
                'E_NOT_FOUND'
            )->withStatus(404);
        }

        return ResponseLib::sendOk([
            'processed' => true,
            'number' => $externalNumber,
        ]);
    }
}
