<?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;

final readonly class ProductController
{
    public function __construct(
        private readonly ShopifyClient $client
    ) {
    }

    /**
     * Ruft alle Produkte aus dem Shopify-Shop ab
     */
    #[Route(path: '/api/shopify/products', method: Method::GET)]
    public function listProducts(): JsonResult
    {
        try {
            $options = [
                'limit' => 50,
                'fields' => 'id,title,variants,images,status,published_at',
            ];

            $products = $this->client->getProducts($options);

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

            return $result;
        }
    }

    /**
     * Ruft ein einzelnes Produkt anhand seiner ID ab
     */
    #[Route(path: '/api/shopify/products/{id}', method: Method::GET)]
    public function getProduct(int $id): JsonResult
    {
        try {
            $product = $this->client->getProduct($id);

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

            return $result;
        }
    }

    /**
     * Erstellt ein neues Produkt
     */
    #[Route(path: '/api/shopify/products', method: Method::POST)]
    public function createProduct(ProductRequest $request): JsonResult
    {
        try {
            $product = $this->client->createProduct([
                'title' => $request->title,
                'body_html' => $request->description ?? '',
                'vendor' => $request->vendor ?? 'Custom Shop',
                'product_type' => $request->productType ?? '',
                'tags' => $request->tags ?? '',
                'variants' => $request->variants ?? [],
                'options' => $request->options ?? [],
                'images' => $request->images ?? [],
            ]);

            $result = new JsonResult([
                'success' => true,
                'data' => $product,
            ]);
            $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;
        }
    }

    /**
     * Aktualisiert ein bestehendes Produkt
     */
    #[Route(path: '/api/shopify/products/{id}', method: Method::PUT)]
    public function updateProduct(int $id, ProductRequest $request): JsonResult
    {
        try {
            $productData = [];

            // Nur die Felder aktualisieren, die tatsächlich im Request enthalten sind
            if (isset($request->title)) {
                $productData['title'] = $request->title;
            }
            if (isset($request->description)) {
                $productData['body_html'] = $request->description;
            }
            if (isset($request->vendor)) {
                $productData['vendor'] = $request->vendor;
            }
            if (isset($request->productType)) {
                $productData['product_type'] = $request->productType;
            }
            if (isset($request->tags)) {
                $productData['tags'] = $request->tags;
            }
            if (isset($request->variants)) {
                $productData['variants'] = $request->variants;
            }
            if (isset($request->options)) {
                $productData['options'] = $request->options;
            }
            if (isset($request->images)) {
                $productData['images'] = $request->images;
            }

            $product = $this->client->updateProduct($id, $productData);

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

            return $result;
        }
    }

    /**
     * Löscht ein Produkt
     */
    #[Route(path: '/api/shopify/products/{id}', method: Method::DELETE)]
    public function deleteProduct(int $id): JsonResult
    {
        try {
            $success = $this->client->deleteProduct($id);

            return new JsonResult([
                'success' => $success,
                'message' => $success ? 'Produkt erfolgreich gelöscht' : 'Produkt konnte nicht gelöscht werden',
            ]);
        } catch (ApiException $e) {
            $result = new JsonResult([
                'success' => false,
                'error' => $e->getMessage(),
            ]);
            $result->status = Status::from($e->getCode() ?: 500);

            return $result;
        }
    }

    /**
     * Sucht nach Produkten
     */
    #[Route(path: '/api/shopify/products/search', method: Method::GET)]
    public function searchProducts(string $query): JsonResult
    {
        try {
            $products = $this->client->searchProducts($query);

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

            return $result;
        }
    }
}
