<?php

namespace PloverCRM\Modules\Automations\Services;

use PloverCRM\Modules\Automations\Database\Schema;

/**
 * Persistence for automation records.
 */
class AutomationRepository
{
    public static function all(): array
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::AUTOMATIONS_TABLE;
        $rows = $wpdb->get_results("SELECT * FROM $table ORDER BY updated_at DESC", ARRAY_A);

        return array_map([self::class, 'hydrate'], $rows ?: []);
    }

    public static function find(int $automationId): ?array
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::AUTOMATIONS_TABLE;
        $row = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM $table WHERE id = %d LIMIT 1", $automationId),
            ARRAY_A
        );

        return $row ? self::hydrate($row) : null;
    }

    public static function getActiveByEvent(string $eventName): array
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::AUTOMATIONS_TABLE;
        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM $table WHERE status = 'active' AND trigger_event = %s ORDER BY id ASC",
                $eventName
            ),
            ARRAY_A
        );

        return array_map([self::class, 'hydrate'], $rows ?: []);
    }

    public static function createFromTemplate(array $template): int
    {
        $definition = $template['definition'] ?? [];
        $definition['meta'] = array_merge($definition['meta'] ?? [], [
            'template_key' => $template['key'],
            'template_name' => $template['name'],
            'template_category' => $template['category'] ?? 'General',
        ]);

        return self::save([
            'name' => $template['name'],
            'description' => $template['description'] ?? '',
            'status' => 'draft',
            'builder_mode' => sanitize_text_field($template['builder_mode'] ?? 'guided'),
            'trigger_event' => $definition['trigger']['event'] ?? '',
            'definition_json' => $definition,
        ]);
    }

    public static function save(array $automation): int
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::AUTOMATIONS_TABLE;
        $now = current_time('mysql');
        $data = [
            'name' => sanitize_text_field($automation['name'] ?? ''),
            'description' => sanitize_textarea_field($automation['description'] ?? ''),
            'status' => sanitize_text_field($automation['status'] ?? 'draft'),
            'builder_mode' => sanitize_text_field($automation['builder_mode'] ?? 'guided'),
            'trigger_event' => sanitize_text_field($automation['trigger_event'] ?? ''),
            'definition_json' => wp_json_encode($automation['definition_json'] ?? []),
            'updated_at' => $now,
        ];

        if (empty($automation['id'])) {
            $data['created_at'] = $now;
            $wpdb->insert($table, $data);

            return (int) $wpdb->insert_id;
        }

        $automationId = (int) $automation['id'];
        $wpdb->update($table, $data, ['id' => $automationId]);

        return $automationId;
    }

    public static function delete(int $automationId): bool
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::AUTOMATIONS_TABLE;

        return (bool) $wpdb->delete($table, ['id' => $automationId], ['%d']);
    }

    public static function updateStatus(int $automationId, string $status): bool
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::AUTOMATIONS_TABLE;

        return false !== $wpdb->update(
            $table,
            [
                'status' => sanitize_text_field($status),
                'updated_at' => current_time('mysql'),
            ],
            ['id' => $automationId],
            ['%s', '%s'],
            ['%d']
        );
    }

    public static function touchLastRun(int $automationId): void
    {
        global $wpdb;

        $table = $wpdb->prefix . Schema::AUTOMATIONS_TABLE;
        $wpdb->update(
            $table,
            [
                'last_run_at' => current_time('mysql'),
                'updated_at' => current_time('mysql'),
            ],
            ['id' => $automationId],
            ['%s', '%s'],
            ['%d']
        );
    }

    private static function hydrate(array $row): array
    {
        $row['id'] = (int) $row['id'];
        $row['definition_json'] = json_decode($row['definition_json'] ?? '[]', true) ?: [];

        return $row;
    }
}
