<?php

namespace App\Modules\HR\Attendance\Models;

use App\Models\User;
use App\Modules\PLATFORM\Settings\Models\Branch;
use Illuminate\Database\Eloquent\Model;

class AttendanceImportLog extends Model
{
    protected $table = 'attendance_import_logs';

    protected $fillable = [
        'attendance_setting_id',
        'branch_id',
        'source_type',
        'file_name',
        'api_endpoint',
        'total_records',
        'processed_records',
        'success_records',
        'failed_records',
        'skipped_records',
        'status',
        'error_log',
        'started_at',
        'completed_at',
        'imported_by',
    ];

    protected $casts = [
        'error_log' => 'array',
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    /**
     * Relationships
     */
    public function setting()
    {
        return $this->belongsTo(AttendanceSetting::class, 'attendance_setting_id');
    }

    public function branch()
    {
        return $this->belongsTo(Branch::class);
    }

    public function importedBy()
    {
        return $this->belongsTo(User::class, 'imported_by');
    }

    /**
     * Scopes
     */
    public function scopeCompleted($query)
    {
        return $query->where('status', 'COMPLETED');
    }

    public function scopeFailed($query)
    {
        return $query->where('status', 'FAILED');
    }

    public function scopeRecent($query, int $days = 30)
    {
        return $query->where('created_at', '>=', now()->subDays($days));
    }

    /**
     * Helper Methods
     */
    public function getDurationAttribute(): ?string
    {
        if (!$this->started_at || !$this->completed_at) {
            return null;
        }

        return $this->started_at->diffForHumans($this->completed_at, true);
    }

    public function getSuccessRateAttribute(): float
    {
        if ($this->total_records === 0) {
            return 0;
        }

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

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

    public function isFailed(): bool
    {
        return $this->status === 'FAILED';
    }

    public function isProcessing(): bool
    {
        return $this->status === 'PROCESSING';
    }
}
