<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Stancl\Tenancy\Database\Concerns\CentralConnection;

/**
 * Records start/end timing for every scheduled (and otherwise console-invoked) command.
 *
 * Lives on the central connection so per-tenant rows written inside an initialized
 * tenant still land in one place for cross-tenant analysis. A row with a null
 * "tenant_id" is a system/central-context execution (or the "tenants:run" wrapper);
 * a row with a "tenant_id" is a single tenant's slice of a fanned-out command.
 */
class CronLog extends Model
{
    use CentralConnection;

    public const STATUS_RUNNING = 'running';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_FAILED = 'failed';

    protected $fillable = [
        'parent_id',
        'command',
        'tenant_id',
        'arguments',
        'options',
        'status',
        'exit_code',
        'hostname',
        'started_at',
        'finished_at',
        'duration_ms',
    ];

    protected $casts = [
        'arguments' => 'array',
        'options' => 'array',
        'exit_code' => 'integer',
        'started_at' => 'datetime',
        'finished_at' => 'datetime',
        'duration_ms' => 'integer',
    ];

    /**
     * The "tenants:run <inner>" wrapper rows and central commands (no tenant context).
     */
    public function scopeSystem(Builder $query): Builder
    {
        return $query->whereNull('tenant_id');
    }

    public function scopeForTenant(Builder $query, string $tenantId): Builder
    {
        return $query->where('tenant_id', $tenantId);
    }

    public function scopeOfCommand(Builder $query, string $command): Builder
    {
        return $query->where('command', $command);
    }

    /**
     * Slowest finished runs first - the headline view for spotting tasks to optimise.
     */
    public function scopeSlowest(Builder $query): Builder
    {
        return $query->whereNotNull('duration_ms')->orderByDesc('duration_ms');
    }
}
