<?php

namespace App\Models;

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

class BulkOperation extends Model
{
    use HasFactory;

    protected $table = 'bulk_operations';

    protected $fillable = [
        'initiated_by',
        'operation_type',
        'entity_type',
        'total_records',
        'processed_records',
        'status',
        'filters',
        'changes',
        'error_message',
        'started_at',
        'completed_at',
    ];

    protected $casts = [
        'total_records' => 'integer',
        'processed_records' => 'integer',
        'filters' => 'array',
        'changes' => 'array',
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    /**
     * User who initiated this operation
     */
    public function initiator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'initiated_by');
    }

    /**
     * Mark operation as started
     */
    public function markAsStarted(): void
    {
        $this->update([
            'status' => 'in_progress',
            'started_at' => now(),
        ]);
    }

    /**
     * Mark operation as completed
     */
    public function markAsCompleted(): void
    {
        $this->update([
            'status' => 'completed',
            'completed_at' => now(),
        ]);
    }

    /**
     * Mark operation as failed
     */
    public function markAsFailed($errorMessage = null): void
    {
        $this->update([
            'status' => 'failed',
            'error_message' => $errorMessage,
            'completed_at' => now(),
        ]);
    }

    /**
     * Update progress
     */
    public function updateProgress($processedCount): void
    {
        $this->update(['processed_records' => $processedCount]);
    }

    /**
     * Get completion percentage
     */
    public function getProgress(): float
    {
        if ($this->total_records === 0) {
            return 0;
        }

        return round(($this->processed_records / $this->total_records) * 100, 2);
    }

    /**
     * Get duration in seconds
     */
    public function getDuration(): int
    {
        if (!$this->started_at) {
            return 0;
        }

        $endTime = $this->completed_at ?? now();
        return (int) $endTime->diffInSeconds($this->started_at);
    }

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

    /**
     * Scope for in-progress operations
     */
    public function scopeInProgress($query)
    {
        return $query->where('status', 'in_progress');
    }

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

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

    /**
     * Scope for specific operation type
     */
    public function scopeOfType($query, $type)
    {
        return $query->where('operation_type', $type);
    }

    /**
     * Scope for specific entity type
     */
    public function scopeForEntity($query, $entityType)
    {
        return $query->where('entity_type', $entityType);
    }

    /**
     * Scope for specific initiator
     */
    public function scopeBy($query, $userId)
    {
        return $query->where('initiated_by', $userId);
    }

    /**
     * Scope for recent operations
     */
    public function scopeRecent($query, $days = 30)
    {
        return $query->where('created_at', '>=', now()->subDays($days));
    }
}

