<?php

declare(strict_types=1);

namespace ApiModel\Action;

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

final class AccountingAction
{
    public function __construct(
        private readonly ChartAccountService $chartAccounts,
        private readonly JournalService $journals
    ) {}

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

        return $this->chartAccounts->listAccounts($ctx['company_id']);
    }

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

        return $this->chartAccounts->createAccount($ctx['company_id'], HttpUtil::parseJson($request));
    }

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

        return $this->chartAccounts->updateAccount($ctx['company_id'], $id, HttpUtil::parseJson($request));
    }

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

        return $this->journals->listEntries($ctx['company_id'], $ctx['branch_id'] ?? null);
    }

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

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

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

        return $this->journals->saveEntry(
            $ctx['company_id'],
            $ctx['branch_id'] ?? null,
            $u['userId'],
            HttpUtil::parseJson($request)
        );
    }

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

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