<?php

namespace WPSN\Modules\Audit;

use WPSN\Core\Logger;

defined('ABSPATH') || exit;

/**
 * Stores per-scan normalized meta-description keys for duplicate detection.
 *
 * Table: wp_wpsn_audit_scan_description_keys
 */
final class AuditDescriptionKeyRepository
{
    private Logger $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    private function table(): string
    {
        global $wpdb;
        return $wpdb->prefix . 'wpsn_audit_scan_description_keys';
    }

    public function upsert(int $scanId, string $objectType, int $objectId, string $objectSubType, string $descriptionKey): void
    {
        global $wpdb;

        $scanId = (int) $scanId;
        $objectType = sanitize_key($objectType);
        $objectId = (int) $objectId;
        $objectSubType = sanitize_key($objectSubType);
        $descriptionKey = (string) $descriptionKey;

        if ($scanId <= 0 || $objectType === '' || $objectId <= 0 || $descriptionKey === '') {
            return;
        }

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

        try {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->replace(
                $table,
                [
                    'scan_id' => $scanId,
                    'object_type' => $objectType,
                    'object_id' => $objectId,
                    'object_subtype' => $objectSubType,
                    'description_key' => $descriptionKey,
                    'created_at' => $now,
                ],
                ['%d', '%s', '%d', '%s', '%s', '%s']
            );
        } catch (\Throwable $e) {
            $this->logger->error('Audit description-key upsert failed: ' . $e->getMessage());
        }
    }

    public function deleteForObject(int $scanId, string $objectType, int $objectId): int
    {
        global $wpdb;

        $scanId = (int) $scanId;
        $objectType = sanitize_key($objectType);
        $objectId = (int) $objectId;
        if ($scanId <= 0 || $objectType === '' || $objectId <= 0) {
            return 0;
        }

        $table = $this->table();

        try {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            return (int) $wpdb->query($wpdb->prepare(
                "DELETE FROM {$table} WHERE scan_id = %d AND object_type = %s AND object_id = %d",
                $scanId,
                $objectType,
                $objectId
            ));
        } catch (\Throwable $e) {
            $this->logger->error('Audit description-key deleteForObject failed: ' . $e->getMessage());
            return 0;
        }
    }

    public function keyForObject(int $scanId, string $objectType, int $objectId): string
    {
        global $wpdb;

        $scanId = (int) $scanId;
        $objectType = sanitize_key($objectType);
        $objectId = (int) $objectId;
        if ($scanId <= 0 || $objectType === '' || $objectId <= 0) {
            return '';
        }

        $table = $this->table();

        try {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $value = $wpdb->get_var($wpdb->prepare(
                "SELECT description_key FROM {$table} WHERE scan_id = %d AND object_type = %s AND object_id = %d LIMIT 1",
                $scanId,
                $objectType,
                $objectId
            ));
            return is_string($value) ? $value : '';
        } catch (\Throwable $e) {
            $this->logger->error('Audit description-key keyForObject failed: ' . $e->getMessage());
            return '';
        }
    }

    /**
     * @return array<int,array{object_id:int,object_subtype:string}>
     */
    public function rowsForKey(int $scanId, string $objectType, string $descriptionKey): array
    {
        global $wpdb;

        $scanId = (int) $scanId;
        $objectType = sanitize_key($objectType);
        $descriptionKey = (string) $descriptionKey;
        if ($scanId <= 0 || $objectType === '' || $descriptionKey === '') {
            return [];
        }

        $table = $this->table();

        try {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $rows = $wpdb->get_results($wpdb->prepare(
                "SELECT object_id, object_subtype FROM {$table} WHERE scan_id = %d AND object_type = %s AND description_key = %s ORDER BY object_id ASC",
                $scanId,
                $objectType,
                $descriptionKey
            ), ARRAY_A);
        } catch (\Throwable $e) {
            $this->logger->error('Audit description-key rowsForKey failed: ' . $e->getMessage());
            return [];
        }

        if (!is_array($rows)) {
            return [];
        }

        $out = [];
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }
            $objectId = isset($row['object_id']) ? (int) $row['object_id'] : 0;
            if ($objectId <= 0) {
                continue;
            }
            $out[] = [
                'object_id' => $objectId,
                'object_subtype' => isset($row['object_subtype']) ? sanitize_key((string) $row['object_subtype']) : '',
            ];
        }

        return $out;
    }

    /**
     * @return array<int,array{object_type:string,key:string,rows:array<int,array{object_id:int,object_subtype:string}>}>
     */
    public function duplicateGroups(int $scanId): array
    {
        global $wpdb;

        $scanId = (int) $scanId;
        if ($scanId <= 0) {
            return [];
        }

        $table = $this->table();

        // Group by object_type + key so posts never mix with terms.
        $sql = "SELECT t.object_type, t.object_id, t.object_subtype, t.description_key
                FROM {$table} t
                INNER JOIN (
                    SELECT object_type, description_key
                    FROM {$table}
                    WHERE scan_id = %d
                    GROUP BY object_type, description_key
                    HAVING COUNT(*) > 1
                ) d ON d.object_type = t.object_type AND d.description_key = t.description_key
                WHERE t.scan_id = %d
                ORDER BY t.object_type ASC, t.description_key ASC, t.object_id ASC";

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $rows = $wpdb->get_results($wpdb->prepare($sql, $scanId, $scanId), ARRAY_A);
        if (!is_array($rows) || empty($rows)) {
            return [];
        }

        return AuditDuplicateKeyGroups::build($rows, 'description_key');
    }

    public function clearAll(): void
    {
        global $wpdb;
        $table = $this->table();

        try {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->query("DELETE FROM {$table}");
        } catch (\Throwable $e) {
            $this->logger->error('Audit description-key clear failed: ' . $e->getMessage());
        }
    }
}
