<?php

declare(strict_types=1);

namespace App\Models;

use App\Enums\ExportStatus;
use App\Enums\UserRole;
use Database\Factories\ExportJobFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ExportJob extends Model
{
    /** @use HasFactory<ExportJobFactory> */
    use HasFactory;

    protected $fillable = [
        'user_id',
        'status',
        'filters',
        'file_path',
        'total_rows',
        'processed_rows',
        'last_member_id',
        'error_message',
        'expires_at',
    ];

    protected function casts(): array
    {
        return [
            'status' => ExportStatus::class,
            'filters' => 'array',
            'expires_at' => 'datetime',
        ];
    }

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

    /**
     * Exports are ownership-scoped (super_admin sees all) rather than
     * branch-scoped — never leak existence of another user's export.
     */
    public function resolveRouteBinding($value, $field = null)
    {
        $query = static::query()->where($field ?? $this->getRouteKeyName(), $value);
        $user = auth()->user();

        if ($user && $user->role !== UserRole::SuperAdmin) {
            $query->where('user_id', $user->id);
        }

        return $query->first();
    }
}
