<?php

namespace WPSN\Modules\BulkTable\Admin;

use WPSN\Core\Container;

defined('ABSPATH') || exit;

final class TermBulkTableJsonExporter
{
    private Container $container;

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

    /**
     * @param array{tax:string,filter:string,s:string} $filters
     */
    public function buildJson(array $filters, int $maxRows = 5000, bool $includeEmptyFields = false): string
    {
        $query = new TermBulkTableQuery($this->container);
        [$items] = $query->fetch($filters, $maxRows, 0);

        $payload = [
            'schema' => 'wpsn-overrides-v1',
            'generated_at' => gmdate('c'),
            'source' => [
                'site_url' => home_url('/'),
                'plugin_version' => defined('WPSN_VERSION') ? WPSN_VERSION : '',
            ],
            'filters' => $filters,
            'items' => [],
        ];

        foreach ($items as $row) {
            $termId = (int) ($row['term_id'] ?? 0);
            $taxonomy = (string) ($row['taxonomy'] ?? '');
            if ($termId <= 0 || $taxonomy === '') {
                continue;
            }

            $link = get_term_link($termId, $taxonomy);
            $link = (!is_wp_error($link) && is_string($link)) ? $link : '';

            $overrides = [
                'seo_title' => (string) ($row['seo_title'] ?? ''),
                'meta_description' => (string) ($row['meta_description'] ?? ''),
                'canonical' => (string) ($row['canonical'] ?? ''),
                'robots_index' => (string) ($row['robots_index'] ?? ''),
                'robots_follow' => (string) ($row['robots_follow'] ?? ''),
                'og_title' => (string) ($row['og_title'] ?? ''),
                'og_description' => (string) ($row['og_description'] ?? ''),
                'og_image' => (string) ($row['og_image'] ?? ''),
                'twitter_title' => (string) ($row['twitter_title'] ?? ''),
                'twitter_description' => (string) ($row['twitter_description'] ?? ''),
                'twitter_image' => (string) ($row['twitter_image'] ?? ''),
            ];

            if (!$includeEmptyFields) {
                $overrides = array_filter(
                    $overrides,
                    static fn($v): bool => is_string($v) && trim($v) !== ''
                );

                if (empty($overrides)) {
                    continue;
                }
            }

            $payload['items'][] = [
                'type' => 'term',
                'id' => $termId,
                'taxonomy' => $taxonomy,
                'slug' => (string) ($row['term_slug'] ?? ''),
                'link' => $link,
                'overrides' => $overrides,
            ];
        }

        $json = wp_json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        return is_string($json) ? $json : '';
    }
}
