<?php

namespace WPSN\Modules\Redirects;

defined('ABSPATH') || exit;

/**
 * Module-specific settings for Redirects + 404 Monitor.
 *
 * Stored separately from the main wpsn_settings option to avoid being overwritten
 * by the main Settings page.
 */
final class RedirectsSettingsRepository
{
    public const OPTION_NAME = 'wpsn_redirects_settings';

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

        return array_replace_recursive($this->defaults(), $value);
    }

    /**
     * @param array<string, mixed> $input
     */
    public function update(array $input): void
    {
        update_option(self::OPTION_NAME, $this->sanitize($input));
    }

    /**
     * @param array<string, mixed> $input
     * @return array<string, mixed>
     */
    public function sanitize(array $input): array
    {
        $out = $this->defaults();

        $out['apply_only_on_404'] = !empty($input['apply_only_on_404']);
        $out['preserve_query']    = !empty($input['preserve_query']);
        $out['enable_regex']      = !empty($input['enable_regex']);
        $out['auto_redirect_post_url_changes'] = !empty($input['auto_redirect_post_url_changes']);

        $out['log_404'] = !empty($input['log_404']);
        $out['log_ignore_logged_in'] = !empty($input['log_ignore_logged_in']);

        $max = isset($input['log_max_rows']) ? (int) $input['log_max_rows'] : (int) $out['log_max_rows'];
        if ($max < 0) {
            $max = 0;
        }
        if ($max > 50000) {
            $max = 50000;
        }
        $out['log_max_rows'] = $max;

        return $out;
    }

    /**
     * @return array<string, mixed>
     */
    public function defaults(): array
    {
        return [
            // Apply redirects only when WP resolves to 404 (safe default).
            'apply_only_on_404' => true,
            // Preserve the original request query string (if destination has no query).
            'preserve_query' => true,
            // Advanced: allow regex redirects. Disabled by default for safety.
            'enable_regex' => false,
            // Automatically create exact 301 redirects when a published post URL changes.
            'auto_redirect_post_url_changes' => true,

            // 404 monitor
            'log_404' => true,
            'log_max_rows' => 500,
            'log_ignore_logged_in' => false,
        ];
    }
}
