<?php

namespace KupShop\GraphQLBundle\ApiShared\Types\Product;

use KupShop\GraphQLBundle\ApiShared\ApiUtil;
use KupShop\GraphQLBundle\ApiShared\Types\Content\EditableContent;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Type;

/**
 * @Type()
 */
class Producer
{
    public $producer;

    public function __construct($producer)
    {
        $this->producer = $producer;
    }

    /**
     * @Field()
     */
    public function id(): int
    {
        return $this->producer['id'];
    }

    /**
     * @Field()
     */
    public function name(): string
    {
        return $this->producer['name'] ?: '';
    }

    /**
     * @Field()
     */
    public function web(): string
    {
        return $this->producer['web'] ?: '';
    }

    /**
     * @Field()
     */
    public function active(): bool
    {
        return $this->producer['active'] == 'Y';
    }

    /**
     * @Field()
     */
    public function photo(): ?\KupShop\GraphQLBundle\ApiShared\Types\Photo
    {
        if (empty($this->producer['image'])) {
            return null;
        }

        return new \KupShop\GraphQLBundle\ApiShared\Types\Photo($this->producer['image']);
    }

    public function blockId(): ?int
    {
        return $this->producer['id_block'] ?? null;
    }

    #[Field(prefetchMethod: 'prefetchProducersBlocks', description: 'Popis.')]
    public function getDescription(array $data): EditableContent
    {
        return new EditableContent(
            $this->blockId(),
            $data[$this->blockId()] ?? [],
            'producers',
            $this->id(),
        );
    }

    public function prefetchProducersBlocks(array $producers): array
    {
        return ApiUtil::fetchBlocksByRootIds(
            array_filter(array_map(fn (Producer $producer) => $producer->blockId(), $producers))
        );
    }

    #[Field(description: 'GPSR - společnost.')]
    public function getCompanyGPSR(): GPSRCompany
    {
        return new GPSRCompany($this->getGPSRData());
    }

    #[Field(description: 'GPSR - dovozce.')]
    public function getImportCompanyGPSR(): GPSRCompany
    {
        return new GPSRCompany($this->getGPSRData('import_'));
    }

    private function getGPSRData(string $field = ''): array
    {
        return [
            'name' => $this->producer[$field.'company_name'] ?? '',
            'street' => $this->producer[$field.'company_street'] ?? '',
            'city' => $this->producer[$field.'company_city'] ?? '',
            'zip' => $this->producer[$field.'company_zip'] ?? '',
            'country' => $this->producer[$field.'company_country'] ?? '',
            'email' => $this->producer[$field.'company_email'] ?? '',
            'web' => $this->producer[$field.'company_web'] ?? '',
        ];
    }
}
