<?php

namespace Controllers;

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

class DocumentListController
{
    private DocumentModel $documentModel;

    public function __construct()
    {
        $this->documentModel = new DocumentModel();
    }

    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);
        }

        try {
            $documents = $this->documentModel->listByUserId($userId);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Database error: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }

        return ResponseLib::sendOk(['documents' => $documents], 'S_OK');
    }
}
