<?php

namespace App\Models\Stats;

class StatJobLog extends BaseStatModel
{
    protected $table = 'stat_job_logs';

    public $timestamps = false;

    protected $casts = [
        'target_date' => 'date',
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
        'created_at' => 'datetime',
    ];

    public function markRunning(): void
    {
        $this->update([
            'status' => 'running',
            'started_at' => now(),
        ]);
    }

    public function markCompleted(int $recordsProcessed = 0): void
    {
        $durationMs = $this->started_at
            ? abs((int) now()->diffInMilliseconds($this->started_at))
            : null;

        $this->update([
            'status' => 'completed',
            'records_processed' => $recordsProcessed,
            'completed_at' => now(),
            'duration_ms' => $durationMs,
        ]);
    }

    public function markFailed(string $errorMessage): void
    {
        $durationMs = $this->started_at
            ? abs((int) now()->diffInMilliseconds($this->started_at))
            : null;

        $this->update([
            'status' => 'failed',
            'error_message' => $errorMessage,
            'completed_at' => now(),
            'duration_ms' => $durationMs,
        ]);
    }
}
