<?php

namespace App\Services;

use App\Models\CronRunLog;

class CronLogService
{
    /**
     * @param  array<string, mixed>  $meta
     */
    public function start(string $command, string $runKey, array $meta = []): CronRunLog
    {
        return CronRunLog::query()->updateOrCreate(
            ['run_key' => $runKey],
            [
                'command' => $command,
                'status' => 'running',
                'started_at' => now(),
                'meta' => $meta,
            ]
        );
    }

    /**
     * @param  array<string, mixed>  $meta
     */
    public function finish(
        CronRunLog $log,
        string $status = 'success',
        ?string $output = null,
        ?string $error = null,
        array $meta = []
    ): void {
        $log->status = $status;
        $log->finished_at = now();
        $log->output = $output;
        $log->error = $error;
        $log->meta = array_merge($log->meta ?? [], $meta);
        $log->save();
    }
}

