<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;

class ProductImport extends Model
{
    public const STATUS_PENDING = 'pending';
    public const STATUS_PROCESSING = 'processing';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_FAILED = 'failed';

    protected $fillable = [
        'user_id',
        'file_path',
        'original_name',
        'status',
        'message',
        'report',
        'started_at',
        'completed_at',
    ];

    protected function casts(): array
    {
        return [
            'report' => 'array',
            'started_at' => 'datetime',
            'completed_at' => 'datetime',
        ];
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function isPending(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    public function isProcessing(): bool
    {
        return $this->status === self::STATUS_PROCESSING;
    }

    public function isCompleted(): bool
    {
        return $this->status === self::STATUS_COMPLETED;
    }

    public function isFailed(): bool
    {
        return $this->status === self::STATUS_FAILED;
    }

    /**
     * Resolve stored file path to absolute path (works when queue/worker run from any CWD).
     */
    public function getResolvedFilePath(): ?string
    {
        $path = trim($this->file_path ?? '', '/\\');
        if ($path === '') {
            return null;
        }
        $disk = Storage::disk(config('filesystems.default', 'local'));
        if ($disk->exists($path)) {
            return $disk->path($path);
        }
        $legacy = storage_path('app' . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path));
        return file_exists($legacy) ? $legacy : null;
    }
}
