<?php

if (!defined('ABSPATH')) {
    exit;
}

final class AISBW_Run_Repository
{
    private wpdb $wpdb;
    private string $table;

    public function __construct()
    {
        global $wpdb;

        $this->wpdb = $wpdb;
        $this->table = $wpdb->prefix . 'aisbw_runs';
    }

    public function start(?int $topic_id, string $run_type, array $input): int
    {
        $this->wpdb->insert(
            $this->table,
            [
                'topic_id' => $topic_id ?: null,
                'run_type' => sanitize_key($run_type),
                'status' => 'started',
                'input_json' => wp_json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                'created_at' => current_time('mysql'),
            ],
            ['%d', '%s', '%s', '%s', '%s']
        );

        return (int) $this->wpdb->insert_id;
    }

    public function finish(int $id, array $output, array $usage = []): void
    {
        $this->wpdb->update(
            $this->table,
            [
                'status' => 'finished',
                'output_json' => wp_json_encode($output, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                'tokens_input' => isset($usage['input']) ? absint($usage['input']) : null,
                'tokens_output' => isset($usage['output']) ? absint($usage['output']) : null,
                'finished_at' => current_time('mysql'),
            ],
            ['id' => $id]
        );
    }

    public function fail(int $id, string $message): void
    {
        $this->wpdb->update(
            $this->table,
            [
                'status' => 'failed',
                'error_message' => sanitize_textarea_field($message),
                'finished_at' => current_time('mysql'),
            ],
            ['id' => $id]
        );
    }

    public function count_today(string $run_type = ''): int
    {
        $start = date('Y-m-d 00:00:00', current_time('timestamp'));

        if ($run_type) {
            return (int) $this->wpdb->get_var(
                $this->wpdb->prepare(
                    "SELECT COUNT(*) FROM {$this->table} WHERE run_type = %s AND created_at >= %s",
                    sanitize_key($run_type),
                    $start
                )
            );
        }

        return (int) $this->wpdb->get_var(
            $this->wpdb->prepare("SELECT COUNT(*) FROM {$this->table} WHERE created_at >= %s", $start)
        );
    }
}
