<?php

namespace MailerPress\Actions\ActionScheduler\Processors;

use MailerPress\Core\Attributes\Action;
use MailerPress\Core\Enums\Tables;
use MailerPress\Services\ContactEngagementClassifier;

class AccessTokenGenerator
{
    #[Action('mailerpress_generate_access_tokens')]
    public function generateMissingTokens(): void
    {
        global $wpdb;
        $table = Tables::get(Tables::MAILERPRESS_CONTACT);

        // Check if table exists
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table}'") === $table;
        if (!$table_exists) {
            delete_option('mailerpress_access_tokens_scheduled');
            return;
        }

        // Check if access_token column exists
        $column_exists = $wpdb->get_results(
            $wpdb->prepare(
                "SHOW COLUMNS FROM {$table} LIKE %s",
                'access_token'
            )
        );
        if (empty($column_exists)) {
            // Column doesn't exist yet, wait for migration
            delete_option('mailerpress_access_tokens_scheduled');
            return;
        }

        // Batch size
        $batchSize = 200;

        // Fetch contacts missing access_token
        $contacts = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT contact_id FROM $table WHERE access_token IS NULL OR access_token = '' LIMIT %d",
                $batchSize
            )
        );

        if (empty($contacts)) {
            delete_option('mailerpress_access_tokens_scheduled');
            return;
        }

        foreach ($contacts as $contact) {
            $token = bin2hex(random_bytes(32));

            while ($wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(*) FROM $table WHERE access_token = %s",
                    $token
                )) > 0) {
                $token = bin2hex(random_bytes(32));
            }

            $wpdb->update(
                $table,
                ['access_token' => $token],
                ['contact_id' => $contact->contact_id],
                ['%s'],
                ['%d']
            );
        }

        // Reschedule this action to run again after 10 seconds
        if (function_exists('as_schedule_single_action')) {
            as_schedule_single_action(time() + 10, 'mailerpress_generate_access_tokens');
        }
    }

    #[Action('mailerpress_recalculate_engagement')]
    public function calculateEngagement()
    {
        global $wpdb;
        $classifier = new ContactEngagementClassifier($wpdb);
        $classifier->queueRecalculationJobs();
    }

    #[Action('mailerpress_recalculate_engagement_batch', priority: 10, acceptedArgs: 2)]
    public function calculateEngagementBatch($offset, $limit)
    {
        global $wpdb;
        (new ContactEngagementClassifier($wpdb))->processBatch((int)$offset, (int)$limit);
    }
}