<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

final class CronModel extends Model
{
    public function startJob(string $jobKey): int
    {
        $stmt = $this->db->prepare("
            INSERT INTO cron_job_logs (job_key, started_at, status)
            VALUES (:job_key, NOW(), 'running')
        ");
        $stmt->execute([':job_key' => $jobKey]);
        return (int) $this->db->lastInsertId();
    }

    public function finishJob(int $id, string $status, string $message = '', int $notifications = 0, int $emails = 0): void
    {
        $stmt = $this->db->prepare("
            UPDATE cron_job_logs
            SET finished_at = NOW(),
                status = :status,
                message = :message,
                created_notifications = :created_notifications,
                created_emails = :created_emails
            WHERE id = :id
        ");
        $stmt->execute([
            ':id' => $id,
            ':status' => $status,
            ':message' => $message,
            ':created_notifications' => $notifications,
            ':created_emails' => $emails,
        ]);
    }

    public function logs(): array
    {
        return $this->db->query("
            SELECT *
            FROM cron_job_logs
            ORDER BY id DESC
            LIMIT 100
        ")->fetchAll();
    }

    public function getState(string $key): ?string
    {
        $stmt = $this->db->prepare("
            SELECT state_value
            FROM cron_job_state
            WHERE state_key = :state_key
            LIMIT 1
        ");
        $stmt->execute([':state_key' => $key]);
        $val = $stmt->fetchColumn();
        return $val !== false ? (string) $val : null;
    }

    public function setState(string $key, string $value): void
    {
        $stmt = $this->db->prepare("
            INSERT INTO cron_job_state (state_key, state_value)
            VALUES (:state_key, :state_value)
            ON DUPLICATE KEY UPDATE state_value = VALUES(state_value)
        ");
        $stmt->execute([
            ':state_key' => $key,
            ':state_value' => $value,
        ]);
    }
}
