<?php

namespace App\Models;

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

class AnalyticsEvent extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'event_type',
        'event_data',
        'ip_address',
        'user_agent',
        'created_at',
    ];

    protected $casts = [
        'event_data' => 'array',
        'created_at' => 'datetime',
    ];

    // Disable updated_at since we only need created_at for events
    public $timestamps = false;

    /**
     * Event types
     */
    public const TYPE_MESSAGE = 'message';
    public const TYPE_CALLBACK = 'callback';
    public const TYPE_SESSION_START = 'session_start';
    public const TYPE_SESSION_END = 'session_end';
    public const TYPE_ERROR = 'error';
    public const TYPE_PAYMENT = 'payment';
    public const TYPE_MENU_VIEW = 'menu_view';
    public const TYPE_CONTENT_VIEW = 'content_view';

    /**
     * Get the user that owns the event
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Scope for events by type
     */
    public function scopeByType($query, string $type)
    {
        return $query->where('event_type', $type);
    }

    /**
     * Scope for events in date range
     */
    public function scopeInDateRange($query, $startDate, $endDate = null)
    {
        $endDate = $endDate ?: now();
        return $query->whereBetween('created_at', [$startDate, $endDate]);
    }

    /**
     * Scope for events by user
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Scope for message events
     */
    public function scopeMessages($query)
    {
        return $query->where('event_type', self::TYPE_MESSAGE);
    }

    /**
     * Scope for callback events
     */
    public function scopeCallbacks($query)
    {
        return $query->where('event_type', self::TYPE_CALLBACK);
    }

    /**
     * Scope for command events
     */
    public function scopeCommands($query)
    {
        return $query->where('event_type', self::TYPE_MESSAGE)
            ->whereRaw("JSON_EXTRACT(event_data, '$.is_command') = true");
    }

    /**
     * Get command name from event data
     */
    public function getCommandAttribute(): ?string
    {
        if ($this->event_type === self::TYPE_MESSAGE && 
            isset($this->event_data['command'])) {
            return $this->event_data['command'];
        }
        
        return null;
    }

    /**
     * Get callback data from event
     */
    public function getCallbackDataAttribute(): ?string
    {
        if ($this->event_type === self::TYPE_CALLBACK && 
            isset($this->event_data['callback_data'])) {
            return $this->event_data['callback_data'];
        }
        
        return null;
    }

    /**
     * Check if event is a command
     */
    public function isCommand(): bool
    {
        return $this->event_type === self::TYPE_MESSAGE &&
               isset($this->event_data['is_command']) &&
               $this->event_data['is_command'] === true;
    }

    /**
     * Get formatted event description
     */
    public function getDescriptionAttribute(): string
    {
        return match($this->event_type) {
            self::TYPE_MESSAGE => $this->isCommand() 
                ? 'Command: ' . ($this->command ?? 'unknown')
                : 'Message: ' . \Illuminate\Support\Str::limit($this->event_data['text'] ?? 'empty', 30),
            self::TYPE_CALLBACK => 'Callback: ' . ($this->callback_data ?? 'unknown'),
            self::TYPE_SESSION_START => 'Session Started',
            self::TYPE_SESSION_END => 'Session Ended',
            self::TYPE_ERROR => 'Error: ' . ($this->event_data['error'] ?? 'unknown'),
            self::TYPE_PAYMENT => 'Payment: ' . ($this->event_data['status'] ?? 'unknown'),
            self::TYPE_MENU_VIEW => 'Menu View: ' . ($this->event_data['menu'] ?? 'unknown'),
            self::TYPE_CONTENT_VIEW => 'Content View: ' . ($this->event_data['page'] ?? 'unknown'),
            default => ucfirst($this->event_type),
        };
    }

    /**
     * Get event icon
     */
    public function getIconAttribute(): string
    {
        return match($this->event_type) {
            self::TYPE_MESSAGE => $this->isCommand() ? '⚡' : '💬',
            self::TYPE_CALLBACK => '🔘',
            self::TYPE_SESSION_START => '🟢',
            self::TYPE_SESSION_END => '🔴',
            self::TYPE_ERROR => '❌',
            self::TYPE_PAYMENT => '💳',
            self::TYPE_MENU_VIEW => '📋',
            self::TYPE_CONTENT_VIEW => '📄',
            default => '📊',
        };
    }
}