<?php

declare(strict_types=1);

namespace Ekdos\Relay;

use Ekdos\N8n\CachePolicy;
use Ekdos\Support\Json;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

final readonly class OnlinePurchasesController extends RelayController
{
    public function index(Request $request, Response $response): Response
    {
        $reply = $this->cachedGet(CachePolicy::Purchases, $this->n8nUrl->onlinePurchases());

        if (!$reply->ok()) {
            return $this->upstreamError($response, $reply, 'Die Online-Käufe konnten nicht aus n8n geladen werden.');
        }

        return $this->listResponse($response, $reply, 'purchases', 'purchases');
    }

    /** Vormals: nur Sascha. */
    public function create(Request $request, Response $response): Response
    {
        $body = $this->body($request);
        $article = self::text($body, 'artikel');
        $marketplace = self::text($body, 'kaufort');
        $date = self::text($body, 'kaufdatum');

        if ($article === '' || $marketplace === '' || preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) {
            return Json::error($response, 'Artikel, Marktplatz und ein gültiges Kaufdatum sind erforderlich.', 400);
        }

        $reply = $this->n8n->post($this->n8nUrl->onlinePurchases(), ['artikel' => $article, 'kaufort' => $marketplace, 'kaufdatum' => $date]);

        if (!$reply->ok()) {
            return $this->upstreamError($response, $reply, 'Der Online-Kauf konnte nicht in n8n gespeichert werden.');
        }

        $this->cache->invalidate(CachePolicy::Purchases[0]);

        return Json::write($response, ['purchase' => $reply->decoded()], 201);
    }

    /** Vormals: nur Svenja. */
    public function complete(Request $request, Response $response): Response
    {
        $id = self::text($this->body($request), 'id');

        if ($id === '') {
            return Json::error($response, 'Die Kaufposition fehlt.', 400);
        }

        $reply = $this->n8n->post($this->n8nUrl->onlinePurchases('/erledigt'), ['id' => $id]);

        if (!$reply->ok()) {
            return $this->upstreamError($response, $reply, 'Der Online-Kauf konnte nicht abgeschlossen werden.');
        }

        $this->cache->invalidate(CachePolicy::Purchases[0]);

        return Json::write($response, $reply->decoded() + ['erledigt_am' => gmdate('c')]);
    }

    /** Vormals: nur Sascha. */
    public function delete(Request $request, Response $response): Response
    {
        $id = self::text($this->body($request), 'id');

        if ($id === '') {
            return Json::error($response, 'Die Kaufposition fehlt.', 400);
        }

        $reply = $this->n8n->post($this->n8nUrl->onlinePurchases('/loeschen'), ['id' => $id]);

        if (!$reply->ok()) {
            return $this->upstreamError($response, $reply, 'Der Online-Kauf konnte nicht gelöscht werden.');
        }

        $this->cache->invalidate(CachePolicy::Purchases[0]);

        return Json::passthrough($response, $reply->body);
    }
}
