<?php

declare(strict_types=1);

namespace ApiModel\Action;

use ApiModel\Service\SalesAdjustmentService;
use ApiModel\Shared\Http\HttpUtil;
use ApiModel\Shared\Support\AuthContext;
use ApiModel\Shared\Support\CompanyContext;
use Psr\Http\Message\ServerRequestInterface;

final class SalesAdjustmentAction
{
    public function __construct(private readonly SalesAdjustmentService $service) {}

    /** @return list<array<string, mixed>> */
    public function listAdjustments(ServerRequestInterface $request): array
    {
        AuthContext::jwtUser($request);
        $ctx = CompanyContext::require($request);
        $queryParams = $request->getQueryParams();
        $type = trim((string) ($queryParams['type'] ?? 'credit_note'));

        return $this->service->listAdjustments($ctx['company_id'], $type);
    }

    /** @return array<string, mixed> */
    public function getAdjustment(ServerRequestInterface $request, string $id): array
    {
        AuthContext::jwtUser($request);
        $ctx = CompanyContext::require($request);

        return $this->service->getAdjustment($ctx['company_id'], $id);
    }

    /** @return array<string, mixed> */
    public function saveAdjustment(ServerRequestInterface $request): array
    {
        $user = AuthContext::jwtUser($request);
        $ctx = CompanyContext::require($request);
        $body = HttpUtil::parseJson($request);

        return $this->service->saveAdjustment($ctx['company_id'], $ctx['branch_id'] ?? null, $user['userId'], $body);
    }

    /** @return array{ok: true} */
    public function deleteAdjustment(ServerRequestInterface $request, string $id): array
    {
        AuthContext::jwtUser($request);
        $ctx = CompanyContext::require($request);
        $this->service->deleteAdjustment($ctx['company_id'], $id);

        return ['ok' => true];
    }
}
