<?php
declare(strict_types=1);

namespace App\Services\Translate;

use App\Core\Database;
use PDO;
use Throwable;

class ZaloroxTranslateBot
{
    public function __construct(private array $config = [], private ?TranslationProviderInterface $provider = null, private ?PDO $pdo = null)
    {
        $this->provider ??= new LocalDictionaryProvider();
    }

    public function translationFor(string $contentType, int $contentId, string $language): ?array
    {
        $language = $this->language($language);
        if ($language === 'tr') {
            return null;
        }

        try {
            $statement = $this->db()->prepare(
                'SELECT *
                 FROM content_translations
                 WHERE content_type = :type
                   AND content_id = :id
                   AND language = :language
                   AND status = "published"
                 LIMIT 1'
            );
            $statement->execute(['type' => $contentType, 'id' => $contentId, 'language' => $language]);
            $row = $statement->fetch();

            return $row ?: null;
        } catch (Throwable) {
            return null;
        }
    }

    public function createDrafts(string $contentType, int $contentId, string $title, string $description = '', string $body = '', ?int $userId = null): void
    {
        foreach (['en', 'de', 'fr'] as $language) {
            $this->createDraft($contentType, $contentId, $language, $title, $description, $body, $userId);
        }
    }

    public function createDraft(string $contentType, int $contentId, string $language, string $title, string $description = '', string $body = '', ?int $userId = null): void
    {
        $language = $this->language($language);
        if ($contentId < 1 || $language === 'tr') {
            return;
        }

        try {
            $statement = $this->db()->prepare(
                'INSERT INTO content_translations
                    (content_type, content_id, language, title, description, body, status, translated_by, provider, created_at, updated_at)
                 VALUES
                    (:content_type, :content_id, :language, :title, :description, :body, "draft", :translated_by, "local_dictionary", NOW(), NOW())
                 ON DUPLICATE KEY UPDATE
                    title = IF(status = "published", title, VALUES(title)),
                    description = IF(status = "published", description, VALUES(description)),
                    body = IF(status = "published", body, VALUES(body)),
                    updated_at = NOW()'
            );
            $statement->execute([
                'content_type' => $contentType,
                'content_id' => $contentId,
                'language' => $language,
                'title' => $this->provider->translate($title, $language),
                'description' => $this->provider->translate($description, $language),
                'body' => $this->provider->translate($body, $language),
                'translated_by' => $userId,
            ]);
        } catch (Throwable) {
            // Draft translation must not block content publishing.
        }
    }

    private function db(): PDO
    {
        if ($this->pdo) {
            return $this->pdo;
        }

        return $this->pdo = Database::connection($this->config ?: null);
    }

    private function language(string $language): string
    {
        $language = substr(preg_replace('/[^a-z]/', '', strtolower($language)) ?: 'tr', 0, 2);

        return in_array($language, ['tr', 'en', 'de', 'fr'], true) ? $language : 'tr';
    }
}
