<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class InventorySyncRun extends Model
{
    /** @use HasFactory<\Database\Factories\InventorySyncRunFactory> */
    use HasFactory;

    public const STATUS_RUNNING = 'running';

    public const STATUS_SUCCESS = 'success';

    public const STATUS_PARTIAL = 'partial';

    public const STATUS_FAILED = 'failed';

    public const STATUS_SKIPPED = 'skipped';

    protected $guarded = [];

    protected $casts = [
        'selection_payload' => 'array',
        'had_errors' => 'boolean',
        'error_codes' => 'array',
        'error_context' => 'array',
        'started_at' => 'datetime',
        'finished_at' => 'datetime',
    ];

    public const STATUS_PENDING = 'pending';

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function scopeCompleted(Builder $query): Builder
    {
        return $query
            ->whereIn('status', [
                self::STATUS_SUCCESS,
                self::STATUS_PARTIAL,
                self::STATUS_FAILED,
                self::STATUS_SKIPPED,
            ])
            ->whereNotNull('finished_at');
    }
}
