<?php

namespace App\Models;

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

class SyncHistory extends Model
{
    use HasFactory;

    protected $table = 'sync_history';

    protected $fillable = [
        'sync_type',
        'external_table',
        'total_processed',
        'imported',
        'updated', // NEW: Track updated records
        'skipped',
        'errors',
        'validation_errors',
        'sync_options',
        'error_details',
        'validation_details',
        'division_sync', // NEW: Track division sync results
        'status',
        'started_at',
        'completed_at',
        'duration_seconds',
        'triggered_by',
    ];

    protected $casts = [
        'sync_options' => 'array',
        'error_details' => 'array',
        'validation_details' => 'array',
        'division_sync' => 'array', // NEW: Cast to array
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

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

    /**
     * Scope for successful syncs
     */
    public function scopeSuccessful($query)
    {
        return $query->where('status', 'completed')->where('errors', 0);
    }

    /**
     * Get the last successful sync for a specific type
     */
    public static function getLastSuccessfulSync($syncType = 'projects')
    {
        return static::where('sync_type', $syncType)
            ->successful()
            ->orderByDesc('completed_at')
            ->first();
    }
}
