<?php

namespace App\Models;

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

class Upload extends Model
{
    use HasFactory;

    protected $fillable = [
        'tenant_id',
        'user_id',
        'filename',
        'original_filename',
        'file_path',
        'status',
        'total_numbers',
        'valid_count',
        'invalid_count',
        'duplicate_count',
        'risky_count',
        'processing_time',
        'default_country',
        'processed_at',
        'error_message',
    ];

    protected $casts = [
        'processed_at'    => 'datetime',
        'processing_time' => 'float',
    ];

    // Status constants
    const STATUS_QUEUED     = 'queued';
    const STATUS_PROCESSING = 'processing';
    const STATUS_COMPLETED  = 'completed';
    const STATUS_FAILED     = 'failed';

    // ── Relations ──────────────────────────────────────────────────────────

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

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

    public function phoneResults(): HasMany
    {
        return $this->hasMany(PhoneResult::class);
    }

    // ── Helpers ────────────────────────────────────────────────────────────

    public function isCompleted(): bool
    {
        return $this->status === self::STATUS_COMPLETED;
    }

    public function getProgressPercentage(): float
    {
        if ($this->total_numbers === 0) return 0;
        $processed = $this->valid_count + $this->invalid_count;
        return round(($processed / $this->total_numbers) * 100, 2);
    }

    public function getValidRate(): float
    {
        $total = $this->valid_count + $this->invalid_count;
        if ($total === 0) return 0;
        return round(($this->valid_count / $total) * 100, 2);
    }
}
