<?php

namespace PloverCRM\Modules\Automations\Services;

use PloverCRM\Modules\Automations\Database\Schema;

/**
 * Persistence for automation run records.
 */
class AutomationRunRepository
{
    public static function startRun(int $automationId, string $eventName, ?int $contactId, array $payload): int
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::RUNS_TABLE;
        $wpdb->insert($table, [
            'automation_id' => $automationId,
            'event_name' => $eventName,
            'contact_id' => $contactId,
            'status' => 'running',
            'payload_json' => wp_json_encode($payload),
            'started_at' => current_time('mysql'),
        ]);

        return (int) $wpdb->insert_id;
    }

    public static function completeRun(int $runId, string $status, array $result = [], string $errorMessage = ''): void
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::RUNS_TABLE;
        $wpdb->update(
            $table,
            [
                'status' => $status,
                'result_json' => wp_json_encode($result),
                'error_message' => $errorMessage ?: null,
                'finished_at' => current_time('mysql'),
            ],
            ['id' => $runId],
            ['%s', '%s', '%s', '%s'],
            ['%d']
        );
    }

    public static function getRecentForAutomation(int $automationId, int $limit = 10): array
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::RUNS_TABLE;
        $query = $wpdb->prepare(
            "SELECT * FROM $table WHERE automation_id = %d ORDER BY started_at DESC LIMIT %d",
            $automationId,
            $limit
        );

        $rows = $wpdb->get_results($query, ARRAY_A) ?: [];

        foreach ($rows as &$row) {
            $row['id'] = (int) $row['id'];
            $row['automation_id'] = (int) $row['automation_id'];
            $row['contact_id'] = isset($row['contact_id']) ? (int) $row['contact_id'] : null;
            $row['payload_json'] = json_decode($row['payload_json'] ?? '[]', true) ?: [];
            $row['result_json'] = json_decode($row['result_json'] ?? '[]', true) ?: [];
        }

        return $rows;
    }
}
