<?php

namespace App\Models;

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

class CloudflareSyncLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'cloudflare_credential_id',
        'cloudflare_zone_id',
        'action',
        'direction',
        'status',
        'records_synced',
        'records_failed',
        'error_message',
        'details',
        'started_at',
        'completed_at',
    ];

    protected $casts = [
        'records_synced' => 'integer',
        'records_failed' => 'integer',
        'details' => 'array',
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    // Statusuri posibile
    const STATUS_PENDING = 'pending';
    const STATUS_RUNNING = 'running';
    const STATUS_SUCCESS = 'success';
    const STATUS_PARTIAL = 'partial';
    const STATUS_FAILED = 'failed';

    // Actiuni posibile
    const ACTION_FULL_SYNC = 'full_sync';
    const ACTION_RECORD_CREATE = 'record_create';
    const ACTION_RECORD_UPDATE = 'record_update';
    const ACTION_RECORD_DELETE = 'record_delete';
    const ACTION_ZONE_IMPORT = 'zone_import';
    const ACTION_ZONE_EXPORT = 'zone_export';

    // Directii
    const DIRECTION_TO_CLOUDFLARE = 'to_cloudflare';
    const DIRECTION_FROM_CLOUDFLARE = 'from_cloudflare';
    const DIRECTION_BIDIRECTIONAL = 'bidirectional';

    /**
     * Relatie cu credential-ul Cloudflare
     */
    public function credential()
    {
        return $this->belongsTo(CloudflareCredential::class, 'cloudflare_credential_id');
    }

    /**
     * Relatie cu zona Cloudflare
     */
    public function cloudflareZone()
    {
        return $this->belongsTo(CloudflareZone::class, 'cloudflare_zone_id');
    }

    /**
     * Scope pentru loguri de succes
     */
    public function scopeSuccessful($query)
    {
        return $query->where('status', self::STATUS_SUCCESS);
    }

    /**
     * Scope pentru loguri cu erori
     */
    public function scopeFailed($query)
    {
        return $query->where('status', self::STATUS_FAILED);
    }

    /**
     * Scope pentru un anumit tip de actiune
     */
    public function scopeForAction($query, string $action)
    {
        return $query->where('action', $action);
    }

    /**
     * Scope pentru o anumita directie
     */
    public function scopeForDirection($query, string $direction)
    {
        return $query->where('direction', $direction);
    }

    /**
     * Creaza un log nou pentru o operatiune
     */
    public static function createLog(
        int $credentialId,
        ?int $zoneId,
        string $action,
        string $direction
    ): self {
        return self::create([
            'cloudflare_credential_id' => $credentialId,
            'cloudflare_zone_id' => $zoneId,
            'action' => $action,
            'direction' => $direction,
            'status' => self::STATUS_PENDING,
            'records_synced' => 0,
            'records_failed' => 0,
            'started_at' => now(),
        ]);
    }

    /**
     * Marcheaza ca in curs de executie
     */
    public function markAsRunning(): void
    {
        $this->update([
            'status' => self::STATUS_RUNNING,
            'started_at' => $this->started_at ?? now(),
        ]);
    }

    /**
     * Marcheaza ca finalizat cu succes
     */
    public function markAsSuccess(int $synced = 0, ?array $details = null): void
    {
        $this->update([
            'status' => self::STATUS_SUCCESS,
            'records_synced' => $synced,
            'details' => $details,
            'completed_at' => now(),
        ]);
    }

    /**
     * Marcheaza ca finalizat partial
     */
    public function markAsPartial(int $synced, int $failed, ?string $error = null, ?array $details = null): void
    {
        $this->update([
            'status' => self::STATUS_PARTIAL,
            'records_synced' => $synced,
            'records_failed' => $failed,
            'error_message' => $error,
            'details' => $details,
            'completed_at' => now(),
        ]);
    }

    /**
     * Marcheaza ca esuat
     */
    public function markAsFailed(string $error, ?array $details = null): void
    {
        $this->update([
            'status' => self::STATUS_FAILED,
            'error_message' => $error,
            'details' => $details,
            'completed_at' => now(),
        ]);
    }

    /**
     * Calculeaza durata operatiunii
     */
    public function getDurationAttribute(): ?int
    {
        if (!$this->started_at) {
            return null;
        }

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

    /**
     * Durata formatata
     */
    public function getFormattedDurationAttribute(): string
    {
        $seconds = $this->duration;

        if ($seconds === null) {
            return '-';
        }

        if ($seconds < 60) {
            return $seconds . 's';
        }

        $minutes = floor($seconds / 60);
        $remainingSeconds = $seconds % 60;

        return $minutes . 'm ' . $remainingSeconds . 's';
    }

    /**
     * Verifica daca a avut erori
     */
    public function hasErrors(): bool
    {
        return $this->status === self::STATUS_FAILED ||
               $this->status === self::STATUS_PARTIAL ||
               $this->records_failed > 0;
    }

    /**
     * Rata de succes
     */
    public function getSuccessRateAttribute(): float
    {
        $total = $this->records_synced + $this->records_failed;

        if ($total === 0) {
            return 100.0;
        }

        return round(($this->records_synced / $total) * 100, 1);
    }

    /**
     * Status label pentru UI
     */
    public function getStatusLabelAttribute(): string
    {
        return match($this->status) {
            self::STATUS_PENDING => 'În așteptare',
            self::STATUS_RUNNING => 'În curs...',
            self::STATUS_SUCCESS => 'Succes',
            self::STATUS_PARTIAL => 'Parțial',
            self::STATUS_FAILED => 'Eșuat',
            default => $this->status,
        };
    }

    /**
     * Status color pentru UI (Bootstrap/Tailwind)
     */
    public function getStatusColorAttribute(): string
    {
        return match($this->status) {
            self::STATUS_PENDING => 'warning',
            self::STATUS_RUNNING => 'info',
            self::STATUS_SUCCESS => 'success',
            self::STATUS_PARTIAL => 'warning',
            self::STATUS_FAILED => 'danger',
            default => 'secondary',
        };
    }

    /**
     * Action label pentru UI
     */
    public function getActionLabelAttribute(): string
    {
        return match($this->action) {
            self::ACTION_FULL_SYNC => 'Sincronizare completă',
            self::ACTION_RECORD_CREATE => 'Creare record',
            self::ACTION_RECORD_UPDATE => 'Actualizare record',
            self::ACTION_RECORD_DELETE => 'Ștergere record',
            self::ACTION_ZONE_IMPORT => 'Import zonă',
            self::ACTION_ZONE_EXPORT => 'Export zonă',
            default => $this->action,
        };
    }

    /**
     * Direction label pentru UI
     */
    public function getDirectionLabelAttribute(): string
    {
        return match($this->direction) {
            self::DIRECTION_TO_CLOUDFLARE => '→ Cloudflare',
            self::DIRECTION_FROM_CLOUDFLARE => '← Cloudflare',
            self::DIRECTION_BIDIRECTIONAL => '↔ Bidirecțional',
            default => $this->direction,
        };
    }

    /**
     * Direction icon pentru UI
     */
    public function getDirectionIconAttribute(): string
    {
        return match($this->direction) {
            self::DIRECTION_TO_CLOUDFLARE => 'fa-arrow-right',
            self::DIRECTION_FROM_CLOUDFLARE => 'fa-arrow-left',
            self::DIRECTION_BIDIRECTIONAL => 'fa-arrows-left-right',
            default => 'fa-sync',
        };
    }
}
