<?php
declare(strict_types=1);

namespace App\Modules\Automation;

use PDO;

final class AutomationEmailOnceRepository
{
    public function __construct(private readonly PDO $pdo)
    {
    }

    public function wasSent(int $ruleId, int $actionId, int $orderId): bool
    {
        if ($ruleId <= 0 || $actionId <= 0 || $orderId <= 0) {
            return false;
        }

        $statement = $this->pdo->prepare(
            'SELECT 1
            FROM automation_email_once_deliveries
            WHERE rule_id = :rule_id
              AND action_id = :action_id
              AND order_id = :order_id
            LIMIT 1'
        );
        $statement->execute([
            'rule_id' => $ruleId,
            'action_id' => $actionId,
            'order_id' => $orderId,
        ]);

        return $statement->fetchColumn() !== false;
    }

    public function markSent(int $ruleId, int $actionId, int $orderId): void
    {
        if ($ruleId <= 0 || $actionId <= 0 || $orderId <= 0) {
            return;
        }

        $statement = $this->pdo->prepare(
            'INSERT INTO automation_email_once_deliveries (rule_id, action_id, order_id, created_at)
            VALUES (:rule_id, :action_id, :order_id, NOW())
            ON DUPLICATE KEY UPDATE created_at = created_at'
        );
        $statement->execute([
            'rule_id' => $ruleId,
            'action_id' => $actionId,
            'order_id' => $orderId,
        ]);
    }
}
