<?php

declare(strict_types=1);

namespace ApiModel\Shared\Support;

final class CompanyContext
{
    public const REQUEST_ATTR = 'companyContext';

    /** @return array{company_id: string, branch_id: ?string}|null */
    public static function fromRequest(\Psr\Http\Message\ServerRequestInterface $request): ?array
    {
        $ctx = $request->getAttribute(self::REQUEST_ATTR);

        return is_array($ctx) ? $ctx : null;
    }

    /** @return array{company_id: string, branch_id: ?string} */
    public static function require(\Psr\Http\Message\ServerRequestInterface $request): array
    {
        $ctx = self::fromRequest($request);
        if ($ctx === null || ! isset($ctx['company_id'])) {
            throw new \ApiModel\Shared\Exceptions\BadRequestException('Se requiere el contexto de empresa (X-Company-Id)');
        }

        return $ctx;
    }
}
