<?php
namespace App\Repositories;

use App\Database\Connection;
use PDO;

class OperationRuleRepository
{
    private Connection $db;

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }

    private function pdo(): PDO
    {
        return $this->db->getPdo();
    }

    public function listRules(bool $activeOnly = false): array
    {
        $sql = "SELECT * FROM operation_rules";
        if ($activeOnly) {
            $sql .= " WHERE is_active = 1";
        }
        $sql .= " ORDER BY is_active DESC, updated_at DESC";
        return $this->pdo()->query($sql)->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    public function dueRules(): array
    {
        return $this->pdo()->query("SELECT * FROM operation_rules
            WHERE is_active = 1
              AND schedule_type <> 'manual'
              AND (next_run_at IS NULL OR next_run_at <= NOW())
            ORDER BY COALESCE(next_run_at, created_at) ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    public function getRule(int $id): ?array
    {
        $stmt = $this->pdo()->prepare("SELECT * FROM operation_rules WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    public function saveRule(array $data, int $userId): int
    {
        $id = (int)($data['id'] ?? 0);
        $values = [
            trim((string)($data['name'] ?? '')),
            (string)($data['description'] ?? ''),
            !empty($data['is_active']) ? 1 : 0,
            (string)($data['entity_scope'] ?? 'lead'),
            json_encode($data['filter'] ?? [], JSON_UNESCAPED_UNICODE),
            json_encode($data['condition'] ?? [], JSON_UNESCAPED_UNICODE),
            json_encode($data['operation'] ?? [], JSON_UNESCAPED_UNICODE),
            (string)($data['schedule_type'] ?? 'manual'),
            json_encode($data['schedule_config'] ?? [], JSON_UNESCAPED_UNICODE),
            !empty($data['dry_run_default']) ? 1 : 0,
        ];

        if ($id > 0) {
            $stmt = $this->pdo()->prepare("UPDATE operation_rules
                SET name = ?, description = ?, is_active = ?, entity_scope = ?, filter_json = ?, condition_json = ?,
                    operation_json = ?, schedule_type = ?, schedule_config_json = ?, dry_run_default = ?,
                    updated_by_user_id = ?, updated_at = NOW()
                WHERE id = ?");
            $stmt->execute(array_merge($values, [$userId, $id]));
            return $id;
        }

        $stmt = $this->pdo()->prepare("INSERT INTO operation_rules
            (name, description, is_active, entity_scope, filter_json, condition_json, operation_json, schedule_type,
             schedule_config_json, dry_run_default, created_by_user_id, updated_by_user_id, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
        $stmt->execute(array_merge($values, [$userId, $userId]));
        return (int)$this->pdo()->lastInsertId();
    }

    public function deleteRule(int $id): void
    {
        $stmt = $this->pdo()->prepare("UPDATE operation_rules SET is_active = 0, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$id]);
    }

    public function markRun(int $id): void
    {
        $stmt = $this->pdo()->prepare("UPDATE operation_rules SET last_run_at = NOW(), next_run_at = NULL, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$id]);
    }
}
