<?php

namespace WPSN\Modules\BulkTable\Admin;

use WPSN\Core\Container;
use WPSN\Domain\SeoDocumentContext;
use WPSN\SEO\SeoMetaRepository;

defined('ABSPATH') || exit;

final class BulkTableExporter
{
    private Container $container;
    private SeoMetaRepository $metaRepo;

    public function __construct(Container $container)
    {
        $this->container = $container;
        $this->metaRepo = $container->get('meta_repo');
    }

    /**
     * @param array{pt:string,status:string,filter:string,s:string} $filters
     */
    public function buildCsv(array $filters, int $maxRows = 5000): string
    {
        $query = new BulkTableQuery($this->container);
        [$items, $total] = $query->fetch($filters, $maxRows, 0);

        $fp = fopen('php://temp', 'r+');
        if (!$fp) {
            return '';
        }

        // Header
        fputcsv($fp, [
            'post_id',
            'post_type',
            'post_status',
            'post_title',
            'post_slug',
            'permalink',

            // override fields (editable)
            'seo_title',
            'meta_description',
            'canonical',
            'robots_index',
            'robots_follow',
            'og_title',
            'og_description',
            'og_image',
            'twitter_title',
            'twitter_description',
            'twitter_image',

            // resolved fields (reference only; ignored on import)
            'resolved_seo_title',
            'resolved_meta_description',
            'resolved_canonical',
            'resolved_og_image',
            'resolved_twitter_image',
        ]);

        foreach ($items as $row) {
            $id = (int) ($row['ID'] ?? 0);
            if ($id <= 0) {
                continue;
            }

            $url = get_permalink($id);
            $url = is_string($url) ? $url : '';

            $ctx = new SeoDocumentContext(SeoDocumentContext::TYPE_SINGULAR, $id, (string) ($row['post_type'] ?? ''), $url, 1);
            $meta = $this->metaRepo->forContext($ctx);

            fputcsv($fp, [
                $id,
                (string) ($row['post_type'] ?? ''),
                (string) ($row['post_status'] ?? ''),
                (string) ($row['post_title'] ?? ''),
                (string) get_post_field('post_name', $id),
                $url,

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

                $meta->title,
                $meta->description,
                $meta->canonical,
                $meta->ogImage,
                $meta->twitterImage,
            ]);
        }

        rewind($fp);
        $csv = stream_get_contents($fp);
        fclose($fp);

        return is_string($csv) ? $csv : '';
    }
}
