<?php

namespace WPSN\Modules\Media;

defined('ABSPATH') || exit;

/**
 * Stores a small journal of CSV imports related to filename drafts / rollback.
 *
 * We keep it lightweight (an option) because entries are small and low-frequency.
 */
final class FilenameCsvHistoryRepository
{
    public const OPTION_NAME = 'wpsn_media_filename_csv_history';

    /**
     * @return array<int,array<string,mixed>>
     */
    public function all(): array
    {
        $raw = get_option(self::OPTION_NAME, []);
        if (!is_array($raw)) {
            return [];
        }

        $out = [];
        foreach ($raw as $e) {
            if (is_array($e) && isset($e['id'], $e['type'], $e['created_at'])) {
                $out[] = $e;
            }
        }
        return $out;
    }

    /**
     * @param array<string,mixed> $entry
     */
    public function append(array $entry): void
    {
        $items = $this->all();

        // Normalize.
        $id = isset($entry['id']) ? (string) $entry['id'] : '';
        if ($id === '') {
            $id = preg_replace('/[^a-zA-Z0-9]/', '', wp_generate_uuid4());
        }

        $type = isset($entry['type']) ? (string) $entry['type'] : 'unknown';
        $created = isset($entry['created_at']) ? (int) $entry['created_at'] : time();
        $userId = isset($entry['user_id']) ? (int) $entry['user_id'] : (int) get_current_user_id();

        $fileName = isset($entry['file_name']) ? (string) $entry['file_name'] : '';
        $fileName = sanitize_text_field($fileName);

        $summary = isset($entry['summary']) && is_array($entry['summary']) ? $entry['summary'] : [];
        $errors = isset($entry['errors']) && is_array($entry['errors']) ? $entry['errors'] : [];

        // Trim errors to keep the option small.
        $cleanErrors = [];
        foreach ($errors as $e) {
            if (!is_string($e)) {
                continue;
            }
            $e = trim(sanitize_text_field($e));
            if ($e === '') {
                continue;
            }
            $cleanErrors[] = $e;
        }
        $cleanErrors = array_slice($cleanErrors, 0, 20);

        $items[] = [
            'id' => $id,
            'type' => $type,
            'created_at' => $created,
            'user_id' => $userId,
            'file_name' => $fileName,
            'summary' => $summary,
            'errors' => $cleanErrors,
        ];

        // Keep last 50.
        if (count($items) > 50) {
            $items = array_slice($items, -50);
        }

        update_option(self::OPTION_NAME, array_values($items), false);
    }

    public function clear(): void
    {
        delete_option(self::OPTION_NAME);
    }
}
