<?php

declare(strict_types=1);

namespace ApiModel\Action;

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

final class ContactAction
{
    public function __construct(private readonly ContactService $service) {}

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

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

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

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

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

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

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

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

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

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