<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class UploadedFile extends Model
{
    use HasFactory;

    protected $fillable = [
        'filename',
        'original_filename',
        'status',
        'total_rows',
        'processed_rows',
        'error_message',
        'file_path',
    ];

    // Status constants
    const STATUS_PENDING = 'pending';
    const STATUS_PROCESSING = 'processing';
    const STATUS_COMPLETED = 'completed';
    const STATUS_FAILED = 'failed';

    /**
     * Get the excel records for this uploaded file
     */
    public function excelRecords(): HasMany
    {
        return $this->hasMany(ExcelRecord::class);
    }

    /**
     * Update processing progress
     */
    public function updateProgress(int $processedRows): void
    {
        $this->update([
            'processed_rows' => $processedRows,
            'status' => self::STATUS_PROCESSING,
        ]);
    }

    /**
     * Mark as completed
     */
    public function markCompleted(): void
    {
        $this->update([
            'status' => self::STATUS_COMPLETED,
            'processed_rows' => $this->total_rows,
        ]);
    }

    /**
     * Mark as failed
     */
    public function markFailed(string $errorMessage): void
    {
        $this->update([
            'status' => self::STATUS_FAILED,
            'error_message' => $errorMessage,
        ]);
    }

    /**
     * Get progress percentage
     */
    public function getProgressPercentageAttribute(): float
    {
        if ($this->total_rows == 0) {
            return 0;
        }

        return ($this->processed_rows / $this->total_rows) * 100;
    }
}

