<?php

declare(strict_types=1);

namespace App\Models;

use App\Enums\ImportStatus;
use App\Models\Concerns\BelongsToBranch;
use Database\Factories\ImportJobFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ImportJob extends Model
{
    /** @use HasFactory<ImportJobFactory> */
    use BelongsToBranch, HasFactory;

    protected $fillable = [
        'user_id',
        'branch_id',
        'status',
        'source_path',
        'error_report_path',
        'total_rows',
        'processed_rows',
        'created_rows',
        'failed_rows',
        'options',
        'error_message',
    ];

    protected function casts(): array
    {
        return [
            'status' => ImportStatus::class,
            'options' => 'array',
        ];
    }

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

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

    /**
     * Cross-branch reads must 404, not 403 — see Member::resolveRouteBinding.
     */
    public function resolveRouteBinding($value, $field = null)
    {
        $query = static::query();
        $user = auth()->user();

        if ($user) {
            $query->visibleTo($user);
        }

        return $query->where($field ?? $this->getRouteKeyName(), $value)->first();
    }
}
