<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ImportLog extends Model
{
    protected $fillable = [
        'user_id',
        'import_mapping_id',
        'original_filename',
        'file_type',
        'total_rows',
        'imported_rows',
        'skipped_rows',
        'error_rows',
        'errors',
        'status',
    ];

    protected $casts = [
        'errors' => 'array',
        'total_rows' => 'integer',
        'imported_rows' => 'integer',
        'skipped_rows' => 'integer',
        'error_rows' => 'integer',
    ];

    public const STATUS_PENDING = 'pending';
    public const STATUS_PROCESSING = 'processing';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_FAILED = 'failed';

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

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

    /**
     * Mark as processing
     */
    public function markAsProcessing(): void
    {
        $this->update(['status' => self::STATUS_PROCESSING]);
    }

    /**
     * Mark as completed
     */
    public function markAsCompleted(int $imported, int $skipped, int $errors, ?array $errorDetails = null): void
    {
        $this->update([
            'status' => self::STATUS_COMPLETED,
            'imported_rows' => $imported,
            'skipped_rows' => $skipped,
            'error_rows' => $errors,
            'errors' => $errorDetails,
        ]);
    }

    /**
     * Mark as failed
     */
    public function markAsFailed(array $errors): void
    {
        $this->update([
            'status' => self::STATUS_FAILED,
            'errors' => $errors,
        ]);
    }

    /**
     * Scope for status
     */
    public function scopeWithStatus($query, string $status)
    {
        return $query->where('status', $status);
    }
}
