<?php

namespace App\Models\Octoparse;

use Illuminate\Database\Eloquent\Model;

class OctoparseImportLog extends Model
{
    protected $table = 'octoparse_import_logs';

    public const STATUS_RUNNING = 'running';
    public const STATUS_SUCCESS = 'success';
    public const STATUS_FAILED  = 'failed';
    public const STATUS_PARTIAL = 'partial';

    protected $fillable = [
        'task_id',
        'status',
        'rows_inserted',
        'rows_updated',
        'rows_failed',
        'rows_fetched',
        'new_record_ids',
        'error_message',
        'metadata',
        'dry_run',
        'triggered_manually',
        'started_at',
        'finished_at',
    ];

    protected $casts = [
        'metadata' => 'array',
        'new_record_ids' => 'array',
        'dry_run' => 'boolean',
        'triggered_manually' => 'boolean',
        'started_at' => 'datetime',
        'finished_at' => 'datetime',
        'rows_inserted' => 'integer',
        'rows_updated' => 'integer',
        'rows_failed' => 'integer',
        'rows_fetched' => 'integer',
    ];

    public function getDurationSecondsAttribute(): ?float
    {
        if (!$this->started_at || !$this->finished_at) {
            return null;
        }
        return $this->finished_at->diffInMilliseconds($this->started_at) / 1000;
    }

    public function getNewRecordsCountAttribute(): int
    {
        return is_array($this->new_record_ids) ? count($this->new_record_ids) : 0;
    }

    public function newRecords()
    {
        $ids = is_array($this->new_record_ids) ? $this->new_record_ids : [];
        return OctoparseRecord::whereIn('id', $ids);
    }

    public function scopeForTask($query, string $taskId)
    {
        return $query->where('task_id', $taskId);
    }
}
