<?php

declare(strict_types=1);

namespace App\Application\Shopify;

use App\Framework\Api\ApiException;
use App\Framework\Attributes\Route;
use App\Framework\Http\Method;
use App\Framework\Http\Status;
use App\Framework\Router\Result\JsonResult;
use App\Infrastructure\Api\ShopifyClient;
use Archive\Config\ApiConfig;

final class ShopController
{
    private ShopifyClient $client;

    public function __construct()
    {
        $this->client = new ShopifyClient(
            ApiConfig::SHOPIFY_SHOP_DOMAIN->value,
            ApiConfig::SHOPIFY_ACCESS_TOKEN->value,
            ApiConfig::SHOPIFY_API_VERSION->value
        );
    }

    /**
     * Ruft Informationen über den Shop ab
     */
    #[Route(path: '/api/shopify/shop', method: Method::GET)]
    public function getShopInfo(): JsonResult
    {
        try {
            $shopInfo = $this->client->getShopInfo();

            return new JsonResult([
                'success' => true,
                'data' => $shopInfo,
            ]);
        } catch (ApiException $e) {
            $result = new JsonResult([
                'success' => false,
                'error' => $e->getMessage(),
            ]);
            $result->status = Status::from($e->getCode() ?: 500);

            return $result;
        }
    }

    /**
     * Ruft die Webhooks des Shops ab
     */
    #[Route(path: '/api/shopify/webhooks', method: Method::GET)]
    public function getWebhooks(): JsonResult
    {
        try {
            $webhooks = $this->client->getWebhooks();

            return new JsonResult([
                'success' => true,
                'data' => $webhooks,
            ]);
        } catch (ApiException $e) {
            $result = new JsonResult([
                'success' => false,
                'error' => $e->getMessage(),
            ]);
            $result->status = Status::from($e->getCode() ?: 500);

            return $result;
        }
    }

    /**
     * Erstellt einen neuen Webhook
     */
    #[Route(path: '/api/shopify/webhooks', method: Method::POST)]
    public function createWebhook(WebhookRequest $request): JsonResult
    {
        try {
            $webhook = $this->client->createWebhook(
                $request->topic,
                $request->address,
                $request->format ?? 'json'
            );

            $result = new JsonResult([
                'success' => true,
                'data' => $webhook,
            ]);
            $result->status = Status::CREATED;

            return $result;
        } catch (ApiException $e) {
            $result = new JsonResult([
                'success' => false,
                'error' => $e->getMessage(),
            ]);
            $result->status = Status::from($e->getCode() ?: 500);

            return $result;
        }
    }
}
