<?php

namespace WPSN\Modules\IndexNow;

defined('ABSPATH') || exit;

final class IndexNowLogRepository
{
    private function table(): string
    {
        global $wpdb;
        return $wpdb->prefix . 'wpsn_indexnow_log';
    }

    /**
     * @param array{status:string,response_code:int,url_count:int,endpoint?:string,payload?:string,error?:string} $row
     */
    public function insert(array $row): int
    {
        global $wpdb;

        $table = $this->table();
        $now = current_time('mysql');

        $data = [
            'status' => sanitize_key((string) ($row['status'] ?? 'ok')),
            'response_code' => (int) ($row['response_code'] ?? 0),
            'url_count' => (int) ($row['url_count'] ?? 0),
            'endpoint' => isset($row['endpoint']) ? (string) $row['endpoint'] : null,
            'payload' => isset($row['payload']) ? (string) $row['payload'] : null,
            'error' => isset($row['error']) ? (string) $row['error'] : null,
            'created_at' => $now,
        ];

        $formats = ['%s', '%d', '%d', '%s', '%s', '%s', '%s'];

        $wpdb->insert($table, $data, $formats);
        return (int) $wpdb->insert_id;
    }

    /**
     * @return array{items: array<int, array<string,mixed>>, total:int}
     */
    public function list(int $page, int $perPage): array
    {
        global $wpdb;

        $table = $this->table();

        $page = max(1, $page);
        $perPage = max(5, min(200, $perPage));
        $offset = ($page - 1) * $perPage;

        $total = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table}");

        $sql = $wpdb->prepare(
            "SELECT * FROM {$table} ORDER BY id DESC LIMIT %d OFFSET %d",
            $perPage,
            $offset
        );

        $items = $wpdb->get_results($sql, ARRAY_A);
        if (!is_array($items)) {
            $items = [];
        }

        return [
            'items' => $items,
            'total' => $total,
        ];
    }
}
